<template>
	<div class="takeOrder">
        <!-- vip -->
        <div class="search-product-box" :class="{fliter:(showCarDetail||showPayBox||showCode||showDelConfirm||isqrcode)}">
            <div class="search-produc"  @click="vipLoginCheckOrder">
                <i class="iconfont icon-sousuo"></i>
                <input type="text" placeholder="请输入要检索的商品名" v-model="product">
            </div>
            <div class="product-box" v-if="productList.length>0" @click.stop="productList=[];product=''">
                <ul class="ul">
                    <li class="product-item" v-for="item in productList" @click.stop="choiceProduct(item)">
                        <span v-text="item.name"></span>
                    </li>
                </ul>
            </div>
        </div>
		<!-- 商品列表 -->
		<div class="goodsBox clearfix" :class="{fliter:(showCarDetail||showPayBox||showCode||showDelConfirm||isqrcode)}">
			<div class="left_bar left" id="left_bar">
				<div id="left_bar_scroll">
					<div v-if="goodsData[0].typeName" class="item flex flex-align-center flex-pack-center" v-for="(oitem,index) in goodsData" v-text="oitem.typeName" :class="{active:curIdx==index}" @click="changeGoodType(index)"></div>
                    <div class="debug-wechat"></div>
				</div>
			</div>
			<div class="right_goods left" id="right_goods">
				<div id="right_goods_scroll">
					<div class="goods_item oneLevel">
						<!-- <div class="goods_li" v-for="(item,ind) in goodsData[curIdx].products" @click="addProduct(item.id, true,null,false)"> -->
						<div class="goods_li" v-for="(item,ind) in goodsData[curIdx].products">
	                        <div class="goodImg left" :class="{'goodImg-border':!item.imageURl}" @click="showImg(item.imageURl)">
	                        	<!-- <img :data-echo="item.imageURl" alt=""> -->
	                        	<!-- <img :src="item.imageURl+'?x-oss-process=image/resize,l_300'" alt=""> -->
	                        	<img v-lazy="item.imageURl+'?x-oss-process=image/resize,l_300'" alt="">
	                        </div>
	                        <div class="goodMsg" @click="beforeSelGoods(item)">
		                        <p class="name" v-text="item.name"></p>
		                        <p class="desc" v-text="item.note" v-if="item.note!=null"></p>
		                        <div class="msgBottom clearfix" :class="item.note!=null?'has-note':''">
                                    <div class="price left" v-if="!item.leaseEnabled" v-text=" '￥' + item.salesPrice"></div>
                                    <div class="price left" style="font-size:.28rem;" v-else>租赁商品</div>
                                    <div class="changeNumber right clearfix">
                                        <!-- <span class="reduceNumber left" :style="{display:(item.goodNumber>0?'inline-block':'none')}" @click="item.goodNumber- -;reduceProduct(item.id)"><i class="iconfont icon-jianshao1"></i></span>
                                        <span class="number left" :style="{display:(item.goodNumber>0?'inline-block':'none')}" v-text="item.goodNumber"></span> -->
                                        <span class="left qty" v-if="!item.leaseEnabled">{{item.stockEnabled?(item.quantity?item.quantity:'无货'):'无限'}}</span>
                                        <span class="left qty" v-else>{{ item.quantity }}</span>
                                        <span class="addNumber left" v-if="item.id!=='0'" :id="item.id"><i class="iconfont icon-tianjia1"></i></span>
                                    </div>
		                        	<div class="addMore right" v-if="item.id==='0'?true:false" @click.stop="openNumberBox(item.id)">自定义网费</div>
		                        	<!-- <div class="addMore right" @click.stop="openNumberBox(item.id)">{{item.id=='0'?'自定义网费':'批量'}}</div> -->
		                        </div>
	                        </div>
	                    </div>
					</div>
		            <div class="goods_item" v-for="(item,ind) in goodsData[curIdx].subTypes" :key="ind" @click.stop="(e)=>traggerType(e)">
		                <p class="title_name" v-text="item.typeName"></p>
		                <!-- <div class="goods_li" v-for="(item,ind) in item.products" @click.stop="addProduct(item.id, true,null,false);"> -->
		                <div class="goods_li" v-for="(item,inde) in item.products" :key="`_${inde}`" >
	                        <div class="goodImg left" :class="{'goodImg-border':!item.imageURl}" @click.stop="showImg(item.imageURl)">
	                        	<!-- <img :data-echo="item.imageURl" alt=""> -->
	                        	<!-- <img :src="item.imageURl+'?x-oss-process=image/resize,l_300'" alt=""> -->
	                        	<img v-lazy="item.imageURl+'?x-oss-process=image/resize,l_300'" alt="">
	                        </div>
	                        <div class="goodMsg" @click.stop="beforeSelGoods(item)">
		                        <p class="name" v-text="item.name"></p>
		                        <p class="desc" v-text="item.note" v-if="item.note!=null"></p>
		                        <div class="msgBottom clearfix" :class="item.note!=null?'has-note':''">
                                    <div class="price left" v-text=" '￥' + item.salesPrice"></div>
                                    <div class="changeNumber right clearfix">
                                        <!-- <span class="reduceNumber left" :style="{display:(item.goodNumber>0?'inline-block':'none')}" @click="item.goodNumber- -;reduceProduct(item.id)"><i class="iconfont icon-jianshao1"></i></span>
                                        <span class="number left" :style="{display:(item.goodNumber>0?'inline-block':'none')}" v-text="item.goodNumber">1</span> -->
                                        <span class="left qty">{{item.stockEnabled?(item.quantity?item.quantity:'无货'):'无限'}}</span>
                                        <span class="addNumber left" :id="item.id"><i class="iconfont icon-tianjia1"></i></span>
                                    </div>
		                        	<!-- <div class="addMore right" @click.stop="openNumberBox(item.id)">批量</div> -->
		                        </div>
	                        </div>
	                    </div>
		            </div>
				</div>
			</div>
		</div>
		
		<!-- 购物车 -->
         <!-- <div style="width:100%;height:1rem;z-index:1;"></div> -->
		<div class="shopCar clearfix" :class="{fliter:(showPayBox||showCode||showDelConfirm||isqrcode)}">
			<div class="carImgBox left flex flex-align-center flex-pack-center" @click="choiceArr.length>0?showCarDetail=true:null">
				<div class="carImg">
					<div class="goodsNumber flex flex-align-center flex-pack-center" v-text="totalPrice.count"></div>
					<i class="iconfont icon-gouwuchekong"></i>
				</div>
			</div>
			<div class="totalPrice left" v-text="'￥'+(totalPrice.amount).toFixed(2)"></div>
            <button type="button" class="confirmBtn right" @click="goPayType()">选好了</button>
			<!-- <button type="button" class="delBtn right" @click="showDelConfirm=true;">取消订单</button> -->
		</div>
       

		<!-- 购物车详情 -->
		<div class="carDetailBox" :style="{display:(showCarDetail?'block':'none')}" @click="showCarDetail=false">
			<div class="carDetail" @click.stop="">
				<!-- <div class="goodsBox" id="carGoodsBox" :style="{height:(0.88*(choiceArr.length-1)+0.44)+'rem'}"> -->
				<div class="goodsBox" id="carGoodsBox">
					<div id="carGoodsBox_scroll">
						<div class="goodItem clearfix" v-for="item in choiceArr">
							<div class="name left">
                                <div class="g-name">{{item.productName}}</div>
                                <div class="add-pei" v-if="item.matchEnabled">
                                    <span class="btn" @click="doShowPeiGoods(item)">添加配品</span>
                                </div>
                            </div>
							<div class="price left" v-text="'￥'+(item.salesPrice/item.quantity).toFixed(2)"></div>
							<div class="changeNumber right">
								<span class="reduceNumber" @click="reduceProduct(item.productId,item)"><i class="iconfont icon-jianshao1"></i></span>
								<span class="number" v-text="item.quantity"></span>
								<span class="addNumber" @click="addProduct(item.productId, false,null,false,item)"><i class="iconfont icon-tianjia1"></i></span>
							</div>
                            <div class="sub-items" v-if="item.masterItemDtos && Array.isArray(item.masterItemDtos) && item.masterItemDtos.length">
                                <div class="goodItem clearfix" v-for="it in item.masterItemDtos">
                                    <div class="name left">
                                        <div class="g-name"><span class="btn">配</span>{{it.productName}}</div>
                                        <!-- <div class="add-pei"> -->
                                        <!-- </div> -->
                                    </div>
                                    <div class="price left" v-text="'￥'+(it.salesPrice/it.quantity).toFixed(2)"></div>
                                    <div class="changeNumber right">
                                        <span class="reduceNumber" @click="reduceAmountForPei(it)"><i class="iconfont icon-jianshao1"></i></span>
                                        <span class="number" v-text="it.quantity"></span>
                                        <span class="addNumber" @click="addAmountForPei(item,it)"><i class="iconfont icon-tianjia1"></i></span>
                                    </div>
                                </div>
                            </div>
                            <!-- 规格 -->
                            <div class="spec-info" v-if="item.specs && Array.isArray(item.specs) && item.specs.length">
                                <!-- 规格：<span class="tag" v-for="(it,ind) in item.specs" :key="ind">{{it}}</span> -->
                                规格：<span class="tag" :key="ind">{{item.specs.join("、")}}</span>
                            </div>
                            <!-- 规格end -->
						</div>
					</div>
				</div>
			</div>
		</div>

        <!-- 确认取消弹出框 -->
        <div class="delConfirmMask" :style="{display:(showDelConfirm?'block':'none')}" @click="showDelConfirm=false">
            <div class="delConfirm position-middle-center" @click.stop="">
                <p class="tipText">订单支付中，确定取消支付？</p>
                <div class="btnGroup">
                    <button type="button" class="cancle" @click="showDelConfirm=false">取消</button>
                    <button type="button" @click="canclePayment()">确定</button>
                </div>
            </div>
        </div>

		<!-- 支付 -->
		<div class="payBox" :style="{display:(showPayBox?'block':'none')}" @click="showSetWrap=false;">
			<div class="returnBtn flex flex-align-center">
				<!-- <i @click="showPayBox=false">&times;</i> -->
				<i @click="returnMoney">&times;</i>
			</div>
			<div class="title flex flex-align-center flex-pack-center">
				<span>订单</span>
			</div>
			<div class="goodsMsg">
                <div class="vip-box clearfix" v-if="vipData">
                    <div class="name left" v-text="vipData.name"></div>
                    <div class="phone left" v-text="vipData.mobile"></div>
                    <div class="del right" @click="cancelVip">解绑会员</div>
                    <div class="price right" v-text="'￥'+vipData.amount"></div>
                </div>
				<div class="goodsListBox" :style="{height:(vipData?'':'68%')}">
					<div class="goodsList" id="goodsList">
						<div id="scroll">
							<div class="goods_li" v-for="(item,ind) in choiceArr">
		                        <div class="goodImg left">
		                        	<img :src="item.productImageURL" :title="item.productName">
		                        </div>
		                        <div class="goodMsg">
			                        <p class="name" v-text="item.productName"></p>
                                    
			                        <div class="msgBottom clearfix">
			                        	<div class="price left" v-text=" '￥' + (item.salesPrice/item.quantity).toFixed(2)"></div>
			                        	<div class="changeNumber right">
			                        		<!-- <span class="reduceNumber" @click="reduceProduct(item.productId)"><i class="iconfont icon-jianshao1"></i></span> -->
			                        		<span class="number" v-text="'×'+item.quantity"></span>
			                        		<!-- <span class="addNumber" @click="addProduct(item.productId, false)"><i class="iconfont icon-tianjia1"></i></span> -->
			                        	</div>
			                        </div>
		                        </div>
                                <div class="sub-goods" style="padding-left:0;font-size:.259rem;color:#dc6060;" v-if="item.specs && Array.isArray(item.specs) && item.specs.length">
                                    规格：<span>{{item.specs.join("、")}}</span>
                                </div>
                                <div class="sub-goods" v-if="item.masterItemDtos && Array.isArray(item.masterItemDtos) && item.masterItemDtos.length">
                                    <div class="goods_li" v-for="(it,index) in item.masterItemDtos">
                                        <div class="goodMsg">
                                            <p class="name"><span class="pei">配</span>{{it.productName}}</p>
                                            <div class="msgBottom clearfix">
                                                <div class="price left" v-text=" '￥' + (it.salesPrice/it.quantity).toFixed(2)"></div>
                                                <div class="changeNumber right">
                                                    <span class="number" v-text="'×'+it.quantity"></span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
		                    </div>
						</div>
					</div>
				</div>
				<div class="totalPriceBox">
					<div class="totalPriceCon" style="text-align:left;">
						<!-- <span class="totalNumber">总计<span v-text="totalPrice.count"></span></span> -->
						<!-- <span class="totalPrice">合计<span v-text="'￥'+(totalPrice.total).toFixed(2)"></span></span> -->
						<span class="totalPrice">优惠:<span v-text="'￥'+(totalPrice.discount).toFixed(2)"></span></span>
						<span class="totalPrice">零头:<span v-text="'￥'+(totalPrice.removeZero).toFixed(2)"></span></span>
						<span class="totalPrice">应付:<span v-text="'￥'+(totalPrice.amount).toFixed(2)"></span></span>
					</div>
                    
                    <div class="seat-number clearfix">
                        <div class="left">
                            <span>座位号：</span>
                        </div>
                        <div class="right">
                            <!-- <span>请填写座位号</span> -->
                            <input type="text" placeholder="请填写座位号" v-model="tableNo" maxlength="10" @click="clickInput($event)">
                        </div>
                    </div>
                    <div class="seat-number clearfix">
                        <div class="" style="display:inline-block;width:40%;">
                            <span style="display:inline-block;">备注:</span>
                            <span style="display:inline-block;">(自选)</span>
                            <input style="width:.25rem;" type="checkbox" v-model="selNotes">
                        </div>
                        <div class="" style="display:inline-block;width:55%;">
                            <!-- <span>请填写座位号</span> -->
                            <input type="text" placeholder="请输入口味、偏好等要求" v-if="!selNotes" v-model="notes" maxlength="120" @click="clickInput($event)">
                            <select name=""  v-if="selNotes" id="" v-model="notes">
                                <option :value="item.message" v-for="(item,index) in notesArr" :key="index">{{item.message.length>9?spliceStr(item.message):item.message}}</option>
                            </select>
                        </div>
                    </div>
				</div>
                <!--  -->
                <div v-if="showDiscount||showZero" :class="showSetWrap?'discount-wipe-zero show-set':'discount-wipe-zero'" @click.stop="" >
                                <div class="wrap">
                                    <div class="discount-set" v-if="showDiscount">
                                        <span>折扣:</span>
                                        <select class="dis-sel" name="" id="" v-model="firstDiscount" >
                                            <option :value="item" v-for="(item,index) in discountVals" :key="index">{{item}}</option>
                                        </select>
                                        <select class="dis-sel" name="" id="" v-model="lastDiscount">
                                            <option :value="item" v-for="(item,index) in discountVals" :key="index">{{item}}</option>
                                        </select>
                                        <!-- <el-select v-model="firstDiscount" placeholder="请选择">
                                            <el-option
                                            v-for="item in discountVals"
                                            :key="item"
                                            :value="item">
                                            </el-option>
                                        </el-select>
                                        <el-select v-model="lastDiscount" placeholder="请选择">
                                            <el-option
                                            v-for="item in discountVals"
                                            :key="item"
                                            :value="item">
                                            </el-option>
                                        </el-select> -->
                                        <div class="now-discount">
                                            <span>当前所选折扣：<b>{{firstDiscount+'.'+lastDiscount}}</b> 折</span>
                                        </div>
                                        <div>
                                            <span>折后价：<b>{{Number(Number(firstDiscount+''+lastDiscount)/100) == 0?totalPrice.amount.toFixed(2):((totalPrice.amount)*Number(Number(firstDiscount+''+lastDiscount)/100)).toFixed(2)}}</b> 元</span>
                                        </div>
                                        <!-- <div v-if="showZero" style="padding-bottom:10px;">
                                            <el-checkbox v-model="checkedWipeZero">抹零</el-checkbox>
                                        </div>
                                        <div class="sure-discount">
                                            <button @click="discountThisOrder">确定</button>
                                        </div> -->
                                        
                                    </div>
                                    <!-- <div v-if="showZero" style="padding-bottom:10px;">
                                        <el-checkbox v-model="checkedWipeZero">抹零</el-checkbox>
                                    </div> -->
                                    <div v-if="showZero" style="padding-bottom:10px;" class="auto-money">
                                        <span class="money" style="font-size:14px;color:red;">自定义金额:</span>
                                        <input type="text" v-model="wipeZeroMoney" placeholder="请输入金额" />
                                    </div>
                                    <div class="sure-discount">
                                        <button @click="discountThisOrder">确定</button>
                                    </div>
                                    <!-- <div class="wipe-set" v-if="showZero">
                                        <button @click="wipeZero">抹零</button>
                                    </div> -->
                                </div>
                                <div class="trag-set" @click.stop="showPwd">
                                    <span>折扣 & 零头</span>
                                </div>
                            </div>
                <!--  -->
			</div>
			<div class="payTypeBox">
                <div class="item">
                    <!-- <p class="vip-no-money" v-if="vipData&&(Number(vipData.amount)<Number((totalPrice.amount).toFixed(2)))">&nbsp;</p> -->
                    <div class="payTypeItem flex flex-align-center flex-pack-center alipay left" v-if="!isOnline" @click="payByType('alipay')">支付宝</div>
                    <div class="payTypeItem flex flex-align-center flex-pack-center scan-code left" v-if="isOnline && !vipData" @click="scanCode">在线支付</div>
                    <div class="payTypeItem flex flex-align-center flex-pack-center scan-code left" v-if="isOnline && (vipData&&(Number(vipData.amount)<Number((totalPrice.amount).toFixed(2))))" @click="scanCode">在线支付</div>
                    <div class="payTypeItem flex flex-align-center flex-pack-center scan-code left" v-if="vipData&&(Number(vipData.amount)>=Number((totalPrice.amount).toFixed(2)))" @click="showBindVipBoxOrPayByVip">会员支付</div>
                    <!-- <div class="payTypeItem flex flex-align-center flex-pack-center scan-code left" v-if="isOnline" @click="showTestPayCode=true">在线支付</div> -->
                    <!-- <div class="payTypeItem flex flex-align-center flex-pack-center money left" @click="scanCode">扫一扫</div> -->
                    <div class="payTypeItem flex flex-align-center flex-pack-center wechat right" v-if="!isOnline" @click="payByType('wechat')">微信</div>
                    <!--  -->
                    <div class="payTypeItem flex flex-align-center flex-pack-center money left" @click="placeOrder('cash')" v-if="clerkCashSales">现金支付</div>
                    <!-- <div class="payTypeItem flex flex-align-center flex-pack-center scan-code left" style="margin-bottom:.25rem;background-color:#4bb7d6;" @click="placeOrder('cash')" v-if="clerkCashSales && vipData">现金支付</div> -->
                    <div class="payTypeItem flex flex-align-center flex-pack-center member right" @click="showBindVipBoxOrPayByVip" v-if="!vipData">绑定会员</div>
                    <div class="payTypeItem flex flex-align-center flex-pack-center member right" @click="doShowCouponList" v-if="vipData">{{isBindCoupon ? "解除优惠券" : "选择优惠券"}}</div>
                    <!-- <div class="payTypeItem flex flex-align-center flex-pack-center scan-code left" style="margin-bottom:.25rem;background-color:#dc6060;" @click="doShowCouponList" v-if="vipData">{{isBindCoupon ? "解除优惠券" : "选择优惠券"}}</div> -->
                    <!-- <div class="payTypeItem flex flex-align-center flex-pack-center only-member left" @click="showBindVipBoxOrPayByVip" v-if="vipData&&(Number(vipData.amount)>=Number((totalPrice.amount).toFixed(2)))">会员支付</div> -->
                    <!-- <div class="payTypeItem flex flex-align-center flex-pack-center only-member left" @click="goVipCharge" v-if="vipData&&(Number(vipData.amount)<Number((totalPrice.amount).toFixed(2)))">会员充值</div> -->
                </div>
                <!-- <div class="item">
                    <div class="payTypeItem flex flex-align-center flex-pack-center money left" @click="placeOrder('cash')" v-if="clerkCashSales && !vipData">现金支付</div>
                    <div class="payTypeItem flex flex-align-center flex-pack-center member right" @click="showBindVipBoxOrPayByVip" v-if="!vipData">会员支付</div>
                    <div class="payTypeItem flex flex-align-center flex-pack-center scan-code left" style="margin-bottom:.25rem" @click="doShowCouponList" v-if="vipData">{{isBindCoupon ? "解除优惠券" : "选择优惠券"}}</div>
                    <div class="payTypeItem flex flex-align-center flex-pack-center only-member left" @click="showBindVipBoxOrPayByVip" v-if="vipData&&(Number(vipData.amount)>=Number((totalPrice.amount).toFixed(2)))">会员支付</div>
                    <div class="payTypeItem flex flex-align-center flex-pack-center only-member left" @click="goVipCharge" v-if="vipData&&(Number(vipData.amount)<Number((totalPrice.amount).toFixed(2)))">会员充值</div>
                </div> -->
			</div>
		</div>

		<!-- 支付宝二维码 -->
		<div class="qrcode" :style="{display:(showCode?'block':'none')}">
        	<p class="title flex flex-align-center flex-pack-center">支付二维码</p>
        	<div class="qrcode_box">
        		<div><img :src="payImgUrl" alt=""></div>
        	</div>
            <div class="tip" v-if="isOnline">
                <p>扫码并支付，即可完成订单。</p>
                <p>请在5分钟内完成支付，超时将自动取消。</p>
                <p v-text="timeDown"></p>
            </div>
            <div class="tip" v-else>
                <p>扫码并支付<strong v-text="'￥'+(totalPrice.amount).toFixed(2)"></strong></p>
                <p>请确认顾客已支付成功！</p>
            </div>
            <div class="btnGroup">
                <button type="button" @click="closeCodeImg()">取消支付</button>
                <button type="button" class="save" @click="payOfflineSuccess()" v-if="!isOnline">完成支付</button>
            </div>
        </div>
        
        <!-- 动画节点 -->
        <div class="goodAnimate"></div>
        
        <!-- 数字小键盘 -->
        <div class="numberMaskBox" v-if="showNumBox" @click="showNumBox=false">
            <div class="numberMask" id="numberMask" @click.stop="">
                <div class="inputBox" v-text="goodNumber"></div>
                <div class="numberBox clearfix">
                    <div class="number" @click="clickNum('1')">1</div>
                    <div class="number" @click="clickNum('2')">2</div>
                    <div class="number" @click="clickNum('3')">3</div>
                    <div class="number" @click="clickNum('4')">4</div>
                    <div class="number" @click="clickNum('5')">5</div>
                    <div class="number" @click="clickNum('6')">6</div>
                    <div class="number" @click="clickNum('7')">7</div>
                    <div class="number" @click="clickNum('8')">8</div>
                    <div class="number" @click="clickNum('9')">9</div>
                    <div class="number" @click="delNumber()">删除</div>
                    <div class="number" @click="clickNum('0')">0</div>
                    <div class="number" @click="saveNumber()">保存</div>
                </div>
            </div>
        </div>

        <!-- 添加会员二维码 -->
        <div class="vipQrcode" :style="{display:isqrcode?'block':'none'}" @click="closeVipCode()">
            <button class="jumpBtn" v-if="clerkMemberSwitch" type="button" @click="closeVipCode(true)">跳过 >></button>
            <div class="vipPhoneBox" @click.stop="">
                <div class="phoneBtn" @click="showEnterPhone=true" v-if="!showEnterPhone">手动输入</div>
                <div class="phoneInput clearfix" v-else>
                    <input class="left" type="tel" placeholder="输入会员手机号（至少4位）" v-model="EnterPhone">
                    <!-- <span class="confirmBtn right" @click="showEnterPhoneFn">确定</span> -->
                    <ul class="moreVip" v-if="vipPhoneList&&vipPhoneList.length">
                        <li v-for="(item, idx) in vipPhoneList" @click="selPhoneVip(item)">
                            <span class="name left" v-text="item.name"></span>
                            <span class="price left" v-text="item.mobile"></span>
                        </li>
                    </ul>
                </div>
            </div>
            <div class="content" style="display:none;">
                <div id="vipQrcode" class="qrcode-border"></div>
                <p class="add-text">为了保障您的权益</p>
                <p class="add-text">请扫码留下您的消费记录</p>
                <p class="add-text">还可以积分哦！</p>
            </div>
        </div>
        <div id="show-img-info" v-if="nowImg===''?false:true" @click.stop="hideImg">
            <img :src="nowImg" alt="" @click.stop="">
            <span class="close" @click="hideImg">关闭</span>
        </div>
        <div id="show-loading-pay" v-if="showPayLoding">
            <div class="loading-box">
                <p class="loading-info">支付中，请勿取消或关闭页面...</p>
                <!-- <div class="cancel-pay" @click="deletePayment(orderId)">{{canDeletepayment?'取消支付':('取消支付('+delPaymentLodingTime+'s)')}}</div> -->
            </div>
        </div>
        <div class="cancel-info" v-if="showCancelInfo">
            <p>取消支付成功！如果顾客已付款，系统会在24小时内将款项原路退回至顾客账户</p>
            <button @click="showCancelInfo=false">确定</button>
        </div>
        <div class="test-pay" v-if="showTestPayCode" @click="showTestPayCode=false">
            <input type="text" v-model="testPayCode" @click.stop="" />
            <button @click.stop="testPay">确定</button>
            <button @click.stop="deletePayment(orderId)">取消</button>
        </div>
        <div class="recharge" v-if="showRecharge">
            <div class="recharge-box" :style="showChargeType?'height:auto;padding:.2rem 0;':''">
                <div class="recharge-tit">会员充值</div>
                <div class="vip-info">
                    <span class="name">会员名称:{{vipData.name}}</span>
                    <span class="count-info right">会员账号:{{vipData.mobile}}</span>
                </div>
                <div class="customize-money" v-if="!showChargeType">
                    <span>自定义金额：</span>
                    <input type="text" v-model="inputVipMoney" name="" id="" placeholder="充值金额" />
                </div>
                <span v-if="!showChargeType">
                    <!-- this.$createScroll('scroll_store'); -->
                    <div class="recharge-rules" id="recharge">
                        <ul>
                            <li v-for="(item,index) in chargeRules" :key="index" @click="chargeVip(item)">{{item.name}}</li>
                        </ul>
                    </div>
                    <div class="confirm-box">
                        <button @click="showRecharge=false">取消</button>
                        <button class="yes" @click="chargeVip(null)">确定</button>
                    </div>
                </span>
                <div class="money-info" v-if="showChargeType">
                    <div class="money-info-box">
                        <div class="back">
                            <span @click="showChargeType=false">返回</span>
                        </div>
                        <span class="amount">￥{{curVipChargeInfo.amount}}</span>
                        <div class="code">流水号：{{curVipChargeInfo.code}}</div>
                    </div>
                    <div class="pay">
                        <button @click="chargePay">在线支付</button>
                    </div>
                </div>
            </div>
        </div>
        <div class="alert-pwd" v-if="showAlertPwd" @click="showAlertPwd=false">
            <div class="alert-pwd-wrap" @click.stop="">
                <div class="inner-wrap">
                    <span>折扣抹零前，请输入密码。</span>
                    <input type="password" name="" @keydown.enter="checkDiscountPwd" v-model="disCountPwd" placeholder="请输入密码" id="" />
                    <div>
                        <button @click="checkDiscountPwd">确定</button>
                    </div>
                </div>
            </div>
        </div>
        <div class="pei-goods-wrap" v-if="showPeiGoods">
            <div class="inner-wrap" @click.stop="">
                <div class="scroll-wrap">
                    <div class="pei-goods">
                        <div class="item" v-for="(it,ind) in peiGoods" :class="{active:nowSelPeiGoodsIds.indexOf(it.id)!=-1}" @click="modifyPeiGoods('add',it)" :key="ind">
                            <div class="info">
                                <div class="item-name">{{it.name}}</div>
                                <div class="item-price">¥{{it.salesPrice}}</div>
                            </div>
                            <!-- <div class="changeNumber right">
                                <span class="reduceNumber" @click="modifyPeiGoods('reduce',it)"><i class="iconfont icon-jianshao1"></i></span>
                                <span class="number">{{it.selCount}}</span>
                                <span class="addNumber" @click="modifyPeiGoods('add',it)"><i class="iconfont icon-tianjia1"></i></span>
                            </div> -->
                        </div>
                    </div>
                </div>
                <span class="cancel" @click.stop="showPeiGoods = false">跳过</span>
                <span class="sure" @click.stop="submitSelPei">选好了</span>
            </div>
        </div>
        <!-- 规格 -->
        <div class="pei-goods-wrap spec-wrap" v-if="showSelSpec" @click="showSelSpec = false">
            <div class="inner-wrap" @click.stop="">
                <div class="scroll-wrap">
                <div class="pei-goods" v-for="(item,index) in specs" :key="index">
                    <div class="spec-name">{{item.name}}</div>
                    <div class="item" :class="{active:(item.seledSpec&&item.seledSpec==it)}" v-for="(it,ind) in item.specs" :key="`_${ind}`" @click="modifySpecs('add',it,item)">
                        <div class="info">
                            <div class="item-name">{{it}}</div>
                        </div>
                    </div>
                </div>
                </div>
                <span class="sure" @click.stop="submitSelSpec">确认</span>
            </div>
        </div>
        <!-- 规格end -->
        <!-- couponList -->
        <div class="coupon-wrap" v-if="showCouponList" @click="showCouponList=false">
            <div class="inner-wrap">
                <div class="couponList" :class="{all_height:(!nowSelCouponGoods||!nowSelCouponGoods.productName)}" @click.stop="">
                    <ul>
                        <li class="coupon-item" :class="{active:(nowSelCoupon&&nowSelCoupon.id==it.id)}" v-for="it in couponList" @click="selCoupon(it)" :key="it.id">
                            <div class="name">{{it.title}}</div>
                            <div class="coupon-name">{{it.productName}}</div>
                            <div class="coupon-time">
                                有效日期：<i>{{new Date(it.beginTime).Format("yyyy/MM/dd hh:mm")}} ~ {{new Date(it.endTime).Format("yyyy/MM/dd hh:mm")}}</i>
                            </div>
                        </li>
                    </ul>
                </div>
                <p class="sel-info" v-if="nowSelCouponGoods&&nowSelCouponGoods.productName">
                    <span>*当前选择的优惠券抵扣商品是：{{nowSelCouponGoods.productName}}</span>
                </p>
                <span class="sure" @click.stop="submitSelCoupon">确认</span>
            </div>
        </div>
        <div class="pei-goods-wrap" style="z-index:101;bgackground:rgba(0,0,0,.59);" v-if="showCouponGoods" @click="showCouponGoods = false">
            <div class="inner-wrap" @click.stop="">
                <div class="scroll-wrap">
                <div class="pei-goods" style="max-height:4.5rem">
                    <div class="item" v-for="(it,ind) in couponGoods" :class="{active:(nowSelCouponGoods&&nowSelCouponGoods.productId==it.productId)}" @click="modifyCouponGoods(it)" :key="ind">
                        <div class="info">
                            <div class="item-name">{{it.productName}}</div>
                        </div>
                    </div>
                </div>
                </div>
                <span class="sure" @click.stop="submitSelCouponGoods">确认</span>
            </div>
        </div>
        <!--  -->
        <!-- 支付错误弹框start -->
        <div class="pay-err-wrap" v-if="showPayErr">
            <div class="pay-err">
                <div class="err-info">{{errMsg}}</div>
                <div class="btn">
                    <button @click.stop="reLoad">关闭</button>
                </div>
            </div>
        </div>
        <!-- 支付错误弹框end -->
        <!--  -->
        <div class="rent-out-wrap" v-if="showRentInfo" @click.stop="cancelRentInfo">
            <div class="form-wrap" @click.stop="">
                <div class="close-btn" @click.stop="cancelRentInfo">
                    &times;
                </div>
                <div class="form-item">
                    <div class="form-name">*选择区域</div>
                    <div class="item-cont">
                        <select name="" id="" v-model="rentForm.areaId" @change.prevent="changeArea">
                            <option :value="it.id" v-for="it in areas" :key="it.id">
                                {{ it.name }}
                            </option>
                        </select>
                    </div>
                </div>
                <div class="form-item">
                    <div class="form-name">*选择机位</div>
                    <div class="item-cont">
                        <select name="" id="" v-model="rentForm.numId" @change.prevent="changeTable">
                            <option :value="it.id" v-for="it in tables" :key="it.id">
                                {{ it.name }}
                            </option>
                        </select>
                    </div>
                </div>
                <div class="form-item">
                    <div class="form-name">*计费规则</div>
                    <div class="item-cont">
                        <select name="" id="" v-model="rentForm.ruleId" @change.prevent="changeRule">
                            <option value="" key="-1">请选择</option>
                            <option :value="it.ruleId" v-for="it in nowSelRentGoodsRules" :key="it.ruleId">
                                {{ it.ruleName }}
                            </option>
                        </select>
                    </div>
                </div>
                <div class="form-item">
                    <div class="form-name">顾客手机</div>
                    <div class="item-cont">
                        <input type="text" v-model="rentForm.mobile" placeholder="手机号(非必填)"/>
                    </div>
                </div>
                <div class="rent-list">
					<div class="rent-head">
						<span class="it">商品</span>
						<span class="it">详情</span>
					</div>
					<div class="rent-goods">
						<div class="r-li">
							<span class="it" v-if="nowSelRentGoods">{{nowSelRentGoods.name}}</span>
							<span class="it">数量:1</span>
						</div>
						<div class="r-li">
							<span class="it">押金</span>
							<span class="it">{{nowSelRentRule ? Number(nowSelRentRule.amount).toFixed(2) : "--"}}</span>
						</div>
						<div class="r-li">
							<span class="it">租赁规则</span>
							<span class="it">{{nowSelRentRule ? nowSelRentRule.ruleName : "--"}}</span>
						</div>
					</div>
				</div>
                <!-- <button class="sub-btn cancel" @click.stop="cancelRentInfo">取消</button> -->
                <button class="sub-btn" @click.stop="sureSelRentInfo">确定</button>
            </div>
        </div>
	</div>
</template>

<script>
import { url } from '@/router/url.js';
import {API_BASE_URL} from "./../../urlConfig/index";
export default {
  	data(){
  		return{
            leaseProductEnabled:false,
            nowSelRentRule:null,
            nowSelRentGoodsRules:[],
            nowSelRentGoods:null,
            rentForm:{
                name:"",
                mobile:"",
                empId:"",
                empName:"",
                ruleId:"",
                productId:"",
                areaId:"",
                numName:"",
                numId:"",
                source:"EMPLOYEE"
            },
            tables:[],
            areas:[],
            showRentInfo:false,
            // 
            errMsg:"",
            showPayErr:false,
            // 
            nowReduceItem:null,
            nowSelNeedSpecItem:null,
            nowSelSpec:[],
            specs:[],
            fromSelSpec:false,
            showSelSpec:false,
            //
            nowSelCoupon:{},
            nowSelCouponGoods:{},
            couponGoods:[],
            couponList:[],
            showCouponGoods:false,
            showCouponList:false,
            //   
            notesArr:[],//备注数组
            selNotes:false,//是否支持选择备注
            wipeZeroMoney:'',
            checkedWipeZero:false,
            showDiscount:false,
            showZero:false,
            disCountPwd:"",
            showAlertPwd:false,
            showSetWrap:false,//是否显示抹零设置窗口
            lastDiscount:0,
            firstDiscount:0,
            discountVals:[0,1,2,3,4,5,6,7,8,9],
            curVipChargeInfo:{},
            showChargeType:false,//当前是否显示会员支付选择方式
            inputVipMoney:"",//会员充值自定义金额
            chargeRules:[],//充值规则
            showRecharge:false,
            canClick:true,
            showTestPayCode:false,//是否显示测试支付框
            testPayCode:"",//测试用code
            showCancelInfo:false,
            showPayLoding:false,//是否显示支付等待
            canDeletepayment:false,//是否能取消支付
            delPaymentLodingTime:30,//支付数秒时间
            nowImg:'',
  			goodsData:[{}], // 商品列表
			curIdx:0, // 当前选择商品分类索引
			showCarDetail: false, // 控制显示购物车详情
			showPayBox: false, // 控制显示支付框
			showCode: false, // 控制显示二维码
            showDelConfirm: false, // 控制显示删除订单
			storeId: '', // 店铺id
			iScrollBtn: false, // 控制非IOS机型下，滚动条样式
			img: url,

			orderId: '', // 订单id
			choiceArr: [], // 选择商品列表

			totalPrice: {
			    count: 0, // 总数量
			    total: 0, // 总计金额
			    discount: 0, // 优惠金额
                amount: 0, // 最终价格
                removeZero:0,
			},

			animateDom: {}, // 动画dom节点
			carDom: {}, // 购物车dom节点
			curPaymentId: '', // 当前支付id

			addGoodBtn: true, // 控制添加商品
			reduceGoodBtn: true, // 控制减少商品
            tableNo:'',//桌号
            notes:'',//备注

            payBtn: true, // 控制支付请求

            payImgUrl: '',

            intervalTimer: '', // 定时器对象

            clerkCashSales: false, // 是否支持现金支付

            newOrderStatus: { // 判断需要生成新订单的状态
                UNFINISHED:1,
                FINISHED:1,
                CANCELED:1,
                REFUNDED:1,
            },

            goodNumber: '', //数字键盘输入商品数量
            curProductId: '', // 当前点击的商品
            showNumBox: false, // 显示数字键盘

            canclePaymentBtn: true, // 控制取消支付
            timeDown:'2:59',
            timeDownTimer:'',

            isOnline: true, // 是否是在线支付
            offlinePayType: '', // 二维码支付时支付类型

            vipLoginApiBtn: true, // 控制会员二维码接口
            isqrcode: false, // 显示添加会员二维码
            vipLoginTimer: undefined, // 会员登录轮询
            vipData: undefined, // 会员数据
            clerkMemberSwitch: false, // 控制是否有跳过按钮
            showEnterPhone: true, // 显示输入手机号
            EnterPhone:'',//手机号
            vipPhoneList: '', //存在多个手机号重复数组
            product:'',//搜索商品
            productList:[],
            payCode:'',
            payType:'PAYCARD',
            delPaymentApiBtn:true,
            paymentBtn:true,
            nowSelNeedPeiItem:null,
            nowSelPeiGoods:[],
            nowSelPeiGoodsIds:[],
            peiGoods:[],
            showPeiGoods:false,
            isBindCoupon:false,
  		}
  	},
    watch:{
        selNotes(val){
            localStorage.setItem("selNotes",JSON.stringify(val));
            if(!val){
                this.notes = "";
            }else{
                if(this.notesArr.length){
                    this.notes = this.notesArr[0].message;
                }
            }
        },
       //搜索获取商品
        product ( val ) {
            if ( !(val.replace(/\s/g,'')) ) {
                this.productList = [];
                return;
            }
            this.$http.get('products/search?storeId='+this.storeId+'&q='+encodeURI(val)).then((res)=>{
                this.productList = res.data;
            })
        },
        EnterPhone ( val ) {
            if ( !(val.replace(/\s/g,'')) ) {
                this.vipPhoneList = [];
                return;
            }
            if(val.length<4){
                return;
            }
            this.$http.get(API_BASE_URL+'v1/member/members-search?storeId='+this.storeId+'&q='+val).then((res)=>{
                for (var i = 0; i < res.data.length; i++) {
                    res.data[i].amount = res.data[i].amount.toFixed(2);
                }
                this.vipPhoneList = res.data;
            })
        },
        showChargeType(val){
            if(!val){
                // this.$createScroll('recharge');
            }
        },
        showPeiGoods(val){
            if(!val){
                this.nowSelPeiGoods = [];
                this.nowSelPeiGoodsIds = [];
                this.nowSelNeedPeiItem = null;
            }
        },
        showPayBox(val){
            if(!val){
                // this.$http({
                //     url:API_BASE_URL+"v1/pos/return-order",
                //     method:"POST",
                //     data:{
                //         orderId:this.orderId
                //     }
                // }).then(res=>{
                //     console.log(res);
                //     if(res.data.result.code == 200){
                //         this.nowSelCoupon = Array.isArray(body.couponInstances) ? body.couponInstances[0] : body.couponInstances;
                //         let body = res.data.data;
                //         this.choiceArr = body.items;
                //         this.totalPrice = {
                //             count:    body.count, // 总数量
                //             total:    body.total, // 总计金额
                //             discount: body.discount, // 优惠金额
                //             amount:   body.amount, // 最终价格
                //             removeZero:   body.removeZero, // 最终价格
                //         }
                //         this.relieveCoupon();
                //     }else if(res.data.result.code == 400){
                //         this.createOrder();
                //     }
                // });
            }
        }
    },
  	methods: {
        changeRule(e){
            if(this.nowSelRentGoodsRules && Array.isArray(this.nowSelRentGoodsRules) && this.nowSelRentGoodsRules.length){
                this.nowSelRentGoodsRules.forEach(it=>{
                    if(it.ruleId == this.rentForm.ruleId){
                        this.nowSelRentRule = it;
                    }
                })
            }
        },
        changeArea(){
            if(this.areas && Array.isArray(this.areas)){
                this.areas.forEach(it=>{
                    if(it.id == this.rentForm.areaId){
                        this.tables = it.nums;
                        this.rentForm.numId = "";
                        this.rentForm.numName = "";
                    }
                })
            }
            this.$forceUpdate();
        },
        changeTable(){
            if(this.tables && Array.isArray(this.tables)){
                this.tables.forEach(it=>{
                    if(it.id == this.rentForm.numId){
                        this.rentForm.numName = it.name;
                    }
                })
            }
            this.$forceUpdate();
        },
        getRegionList(){
            this.$http({
                url:"region/list",
                method:"POST",
                data:{
                    storeId:this.storeId
                }
            }).then(res=>{
                if(res.data && Array.isArray(res.data) && res.data.length){
                    this.areas = res.data;
                }
            })
        },
        cancelRentInfo(){
            this.rentForm = {
                name:"",
                mobile:"",
                empId:"",
                empName:"",
                ruleId:"",
                productId:"",
                areaId:"",
                tableNo:"",
                numId:"",
                source:"EMPLOYEE"
            }
            this.showRentInfo = false;
            this.nowSelRentRule = null;
        },
        sureSelRentInfo(){
            console.log(this.rentForm);
            if(!this.rentForm.numId){
                this.$message({
                    message: '请选择机位',
                    showClose: true,
                    customClass: 'error'
                });
                return;
            }
            if(this.rentForm.numName=="" || String(this.rentForm.numName)=="null" || String(this.rentForm.numName)=="undefined"){
                this.$message({
                    message: '请选择机位',
                    showClose: true,
                    customClass: 'error'
                });
                return;
            }
            // if(!this.rentForm.mobile){
            //     this.$message({
            //         message: '请填写顾客手机号',
            //         showClose: true,
            //         customClass: 'error'
            //     });
            //     return;
            // }
            // if ( !(/^1[3|4|5|6|7|8|9][0-9]{9}$/.test(this.rentForm.mobile)) ) {
            //     this.$message.error({
            //         message: "请输入正确的手机号",
            //         customClass: 'error'
            //     });
            //     return;
            // }
            if(!this.rentForm.ruleId){
                this.$message({
                    message: '请选择计费规则',
                    showClose: true,
                    customClass: 'error'
                });
                return;
            }else{
                //
                const rentInfo = {
                    areaId:this.rentForm.areaId,
                    numId:this.rentForm.numId,
                }
                localStorage.setItem("rentInfo",JSON.stringify({...rentInfo,time:new Date().getTime()}))
                if(this.rentForm.mobile){
                    localStorage.setItem("rentMobile",JSON.stringify({rentMobile:this.rentForm.mobile,time:new Date().getTime()}))
                }
                //
                this.nowSelRentGoodsRules.forEach(it=>{
                    if(it.ruleId == this.rentForm.ruleId){
                        if(it.amount){
                            this.rentForm.authCode = "";
                            this.scanCodeForRent();
                            this.$forceUpdate();
                        }else{
                            this.rentForm.authCode = undefined;
                            this.confirmPaymentForRent();
                        }
                    }
                })
            }
        },
        scanCodeForRent(){
            let _this = this;
            this.canDeletepayment = false;
            wx.scanQRCode({
                needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                success: function (res) {
                    var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                    var resultArr = result.split(",");
                    // 支付
                    _this.payCode = resultArr[resultArr.length-1];
                    _this.showPayLoding = true;
                    _this.showPayBox = false;
                    if(result === 'scan resultStr is here'||_this.payCode === ''||result===''){
                        _this.$message({
                            message: '支付失败，请重新扫描。',
                            customClass: 'error'
                        })
                        _this.showPayLoding = false;
                        return;
                    }
                    // 过滤错误的支付码
                    if(!_this.payCode || String(_this.payCode).trim().length < 18){
                        _this.$message({
                            message: '付款码不完整，请摆正位置，正方位扫码',
                            customClass: 'error',
                            duration:5900,
                        })
                        _this.showPayLoding = false;
                        return;
                    }
                    _this.rentForm.authCode = _this.payCode;
                    _this.confirmPaymentForRent();
                },
                fail:function(res){
                    _this.$message({
                        message: '网络有误，请检查本地网络',
                        showClose: true,
                        customClass: 'error'
                    });
                    return;
                }
            });
        },
        confirmPaymentForRent(){
            // if(!this.rentForm.authCode){
            //     return;
            // }
            if(!this.canClick){
                return;
            }
            this.canClick = false;
            this.showPayLoding = true;
            this.$http({
                url:`${API_BASE_URL}v1/call/create/lease/order`,
                method:"POST",
                data:{
                    ...this.rentForm,
                    storeId:this.storeId,
                }
            }).then(res=>{
                this.showPayLoding = false;
                this.showRentInfo = false;
                this.$message({
                    message: "操作成功",
                    customClass: 'success'
                });
                this.cancelRentInfo();
                this.$router.push({path:'/buySuccessForRent',query:{addTime:new Date(res.data.leaseProductOrder.addTime).getTime(),totalAmount:res.data.leaseProductOrder.totalAmount}});//跳转购买成功页面
                setTimeout(()=>{
                    this.canClick = true;
                },500);
            }).catch(err=>{
                this.showPayLoding = false;
                setTimeout(()=>{
                    this.canClick = true;
                },500);
            })
        },
        // 
        reLoad(){
            // window.location.reload(true);
            this.showPayErr = false;
            this.errMsg = "";
        },
        // 
          beforeCloseSpec(){
            this.nowSelNeedSpecItem = null;
            this.nowSelSpec = [];
            this.fromSelSpec = false;
            this.showSelSpec = false;
        },
        modifySpecs(type,it,item){
            item.seledSpec = it;
            console.log(this.specs);
            let nowSelSpec = [];
            if(this.specs && Array.isArray(this.specs) && this.specs.length){
                this.specs.forEach(it=>{
                    if(it.seledSpec){
                        nowSelSpec.push(it.seledSpec);
                    }
                })
            }
            console.log(nowSelSpec)
            this.nowSelSpec = nowSelSpec;
            this.$forceUpdate();
        },
        submitSelSpec(){
            if(!this.nowSelSpec || !this.nowSelSpec.length ){
                this.$message({
                    message: "请选择规格",
                    customClass: 'error'
                });
                return;
            }
            console.log(this.nowSelSpec);
            if(this.nowSelSpec.length!=this.specs.length){
                this.$message({
                    message: "请完整选择规格",
                    customClass: 'error'
                });
                return;
            }
            // 
            this.goodSearch = '';
            if ( this.upBtn ) return;
            if ( this.nowSelNeedSpecItem.id == '0' ) {
                this.showCustomPrice = true;
                this.customPrice = '';
                setTimeout(()=>{
                    $('#customPriceInput').focus();
                })
                return;
            }
            this.fromSelSpec = true;
            this.addProduct( this.nowSelNeedSpecItem.id );
            this.canClick = false;
            setTimeout(()=>{
                this.canClick = true;
            },500);
            // 
        },
        // 
        submitSelCoupon(){
            let productId = "";
            try {
                if(this.nowSelCoupon.products && Array.isArray(this.nowSelCoupon.products) && this.nowSelCoupon.products.length > 1){
                    if(!this.nowSelCouponGoods || !this.nowSelCouponGoods.productName){
                        this.$message({
                            message: '请选择优惠券所需抵扣的商品',
                            showClose: true,
                            customClass: 'error'
                        });
                        return;
                    }else{
                        productId = this.nowSelCouponGoods.productId;
                    }
                }else{
                    let ids = this.nowSelCoupon.productId.split(",");
                    if(ids.length > 1){
                        productId = this.nowSelCoupon.products[0].productId;
                    }else{
                        productId = this.nowSelCoupon.productId;
                    }
                }
            } catch (error) {
                this.$message({
                    message: '优惠券选择有误，无对应商品优惠。',
                    showClose: true,
                    customClass: 'error'
                });
				return;
            }
            

            if(!this.nowSelCoupon.productId||!this.nowSelCoupon.code){
                this.$message({
                    message: '请重新选择优惠券',
                    showClose: true,
                    customClass: 'error'
                });
                return;
            }

            if(!this.canClick){
                return;
            }
            this.canClick = false;

            this.$http.put('orders/'+this.orderId+'/attachCouponInstance?couponInstanceCode='+this.nowSelCoupon.code+"&productId="+productId).then((res)=>{ 

                setTimeout(()=>{
                    this.canClick = true;
                },500);
                
                this.isBindCoupon = true;
                let body = res.data;
                this.choiceArr = body.items;
                this.totalPrice = {
                    count: body.count, // 总数量
                    total: body.total, // 总计金额
                    discount: body.discount, // 优惠金额
                    amount: body.amount, // 最终价格
                    removeZero: body.removeZero, // 最终价格
                }
                this.addGoodBtn = true;
                this.showCouponList = false;
            }).catch(()=>{
                setTimeout(()=>{
                    this.canClick = true;
                },500);
                this.nowSelCoupon = {};
                this.nowSelCouponGoods = {};
                this.couponGoods = [];
            })
        },
        selCoupon(it){
            this.nowSelCouponGoods = {};
            this.nowSelCoupon = it;
            this.couponGoods = it.products;
            if(Array.isArray(it.products) && it.products.length==1){
                this.nowSelCouponGoods = it.products[0];
            }
            if(Array.isArray(it.products) && it.products.length>1){
                this.showCouponGoods = true;
            }
            console.log("nowSelCouponGoods",this.nowSelCouponGoods)
            // this.showCouponList = false;
        },
        submitSelCouponGoods(){
            this.showCouponGoods = false;
            this.showCouponList = false;
            this.submitSelCoupon();
        },
        modifyCouponGoods(item){
            this.nowSelCouponGoods = item;
        },
        relieveCoupon(relieveMember = false){
            let productId = "";
            // let nowSelCouponItem = sessionStorage.getItem("nowSelCouponItem") ? JSON.parse(sessionStorage.getItem("nowSelCouponItem")) : null;
            if(this.nowSelCouponGoods && this.nowSelCouponGoods.productId){
                productId = this.nowSelCouponGoods.productId
            }
            this.$http.put('orders/'+this.orderId+'/relieveCouponInstance?couponInstanceCode='+this.nowSelCoupon.code+"&productId="+productId).then((res)=>{
                if(relieveMember){
                    this.$http.put('orders/'+this.orderId+'/relieveMember').then((res)=>{
                        this.vipData = '';
                        let body = res.data;
                        this.choiceArr = body.items;
                        this.totalPrice = {
                            count: body.count, // 总数量
                            total: body.total, // 总计金额
                            discount: body.discount, // 优惠金额
                            amount: body.amount, // 最终价格
                            removeZero: body.removeZero, // 最终价格
                        }
                    }).catch(()=>{

                    })
                    this.addGoodBtn = true;
                    this.showCouponList = false;
                    this.isBindCoupon = false;
                    this.nowSelCoupon = {};
                    this.nowSelCouponGoods = {};
                    return;
                }
                let body = res.data;
                this.choiceArr = body.items;
                this.totalPrice = {
                    count: body.count, // 总数量
                    total: body.total, // 总计金额
                    discount: body.discount, // 优惠金额
                    amount: body.amount, // 最终价格
                    removeZero: body.removeZero, // 最终价格
                }
                this.addGoodBtn = true;
                this.showCouponList = false;
                this.isBindCoupon = false;
                this.nowSelCoupon = {};
                this.nowSelCouponGoods = {};
            }).catch(()=>{

            })
        },
        //   
          doShowCouponList(){
              if(this.isBindCoupon){
                  this.relieveCoupon();
                  return;
              }
              let choiceArrIds = [];
            if(this.choiceArr && Array.isArray(this.choiceArr) && this.choiceArr.length){
                this.choiceArr.forEach(it=>{
                    choiceArrIds.push(it.productId);
                })       
            }
              this.$http({
                  url:`${this.vipData.memberId}/coupon-instance`,
                  method:"GET",
                  params:{
                      storeId:this.storeId,
                      page:0,
                      size:1000
                  }
              }).then(res=>{
                   if(res.data.couponInstances && Array.isArray(res.data.couponInstances) && res.data.couponInstances.length){
                        res.data.couponInstances.forEach(it=>{
                            let products = [];
                            let productIds = it.productId.split(",");
                            let productNames = it.productName.split(",");
                            console.log("productIds",productIds)
                            if(productIds && Array.isArray(productIds) && productIds.length){
                                productIds.forEach((ite,ind)=>{
                                    if(choiceArrIds.indexOf(ite)!=-1){
                                        let obj = {
                                            productId:ite,
                                            productName:productNames[ind]
                                        }
                                        products.push(obj);
                                    }
                                })
                            }
                            it.products = products;
                        })
                    }
                    console.log("res.data.couponInstances",res.data.couponInstances)
                  this.couponList = res.data.couponInstances;
                  if(!res.data.totalElements){
                      this.$message({
                        message: "暂无优惠券",
                        showClose: true,
                        customClass: 'error'
                    });
                    return;
                  }
                  this.showCouponList = true;
              })
          },
          reduceAmountForPei(it){
            if(!this.canClick){
                return;
            }
            this.canClick = false;
            this.$http({
                url:`orders/${this.orderId}/remove/match`,
                method:"POST",
                data:{
                    orderItemId:it.id,
                    productCount:1
                }
            }).then(res=>{
                setTimeout(()=>{
                    this.canClick = true;
                },1000);
                this.$message({
                    message: "操作成功",
                    showClose: true,
                    customClass: 'success'
                });
                //
                let body = res.data;
                this.choiceArr = body.items;
                this.totalPrice = {
                    count: body.count, // 总数量
                    total: body.total, // 总计金额
                    discount: body.discount, // 优惠金额
                    amount: body.amount, // 最终价格
                    removeZero: body.removeZero, // 最终价格
                }
                this.addGoodBtn = true;
                // 
                // this.returnMoney(false);
                return;
            }).catch(err=>{
                setTimeout(()=>{
                    this.canClick = true;
                },1000);
            })
        },
        addAmountForPei(item,it){
            if(!this.canClick){
                return;
            }
            this.canClick = false;
            let data = {
                    orderItemId:item.id,
                    orderId:this.orderId,
                    matchParams:[
                        {
                            masterItemId:it.id,
                            productId:it.productId,
                            productCount:1,
                            amount:(it.salesPrice / it.quantity).toFixed(2),
                        }
                    ]
                }
                this.$http({
                    url:`orders/${this.orderId}/add/match`,
                    method:"POST",
                    data
                }).then(res=>{
                    this.showPeiGoods = false;
                    this.$message({
                        message: "操作成功",
                        showClose: true,
                        customClass: 'success'
                    });
                    //
                    let body = res.data;
                    this.choiceArr = body.items;
                    this.totalPrice = {
                        count: body.count, // 总数量
                        total: body.total, // 总计金额
                        discount: body.discount, // 优惠金额
                        amount: body.amount, // 最终价格
                        removeZero: body.removeZero, // 最终价格
                    }
                    this.addGoodBtn = true;
                    //
                    setTimeout(()=>{
                        this.canClick = true;
                    },1000);
                    // this.returnMoney(false);
                }).catch(err=>{
                    setTimeout(()=>{
                        this.canClick = true;
                    },1000);
                })
        },
        modifyPeiGoods(type,item){
        //    if(this.nowSelPeiGoods!=null && item.productId != this.nowSelPeiGoods.productId){
        //        this.$message({
        //             message: "暂支持添加单个配品",
        //             showClose: true,
        //             customClass: 'error'
        //         });
        //        return;
        //    }
        //     if(type == "add"){
        //         item.selCount++;
        //         this.nowSelPeiGoods = item;
        //     }else{
        //         item.selCount--;
        //         if(item.selCount <= 0){
        //             item.selCount = 0;
        //             this.nowSelPeiGoods = null;
        //             return;
        //         }
        //     }
            if(type == "add"){
                let nowSelPeiGoods = JSON.parse(JSON.stringify(this.nowSelPeiGoods));
                
                let flag = true;
                let index;
                if(nowSelPeiGoods && Array.isArray(nowSelPeiGoods) && nowSelPeiGoods.length){
                    nowSelPeiGoods.forEach((it,ind)=>{
                        if(it.id == item.id){
                            flag = false;
                            index = ind;
                        }
                    })
                }
                if(flag){
                    nowSelPeiGoods.push(item);
                }else{
                    nowSelPeiGoods.splice(index,1);
                }

                let nowSelPeiGoodsIds = [];
                nowSelPeiGoods.forEach(it=>{
                    nowSelPeiGoodsIds.push(it.id);
                });
                this.nowSelPeiGoods = nowSelPeiGoods;
                this.nowSelPeiGoodsIds = nowSelPeiGoodsIds;
            }
        },
        submitSelPei(){
            if(this.peiGoods && Array.isArray(this.peiGoods) && this.peiGoods.length){
                if(!this.canClick){
                    return;
                }
                this.canClick = false;
                let matchParams = [];
                if(this.nowSelPeiGoods && Array.isArray(this.nowSelPeiGoods) && this.nowSelPeiGoods.length){
                    this.nowSelPeiGoods.forEach(it=>{
                        let obj = {
                            masterItemId:"",
                            productId:it.id,
                            productCount:1,
                            amount:it.salesPrice,
                        }
                        matchParams.push(obj);
                    })
                }
                if(!matchParams.length){
                    this.$message({
                        message: "请选择配品",
                        showClose: true,
                        customClass: 'error'
                    });
                    this.canClick = true;
                    return;
                }
                let data = {
                    orderItemId:this.nowSelNeedPeiItem.id,
                    orderId:this.orderId,
                    matchParams
                    // masterItemId:"",
                    // productId:this.nowSelPeiGoods.id,
                    // productCount:this.nowSelPeiGoods.selCount,
                    // amount:Number(this.nowSelPeiGoods.selCount)*Number(this.nowSelPeiGoods.salesPrice),
                }
                this.$http({
                    url:`orders/${this.orderId}/add/match`,
                    method:"POST",
                    data
                }).then(res=>{
                    this.showPeiGoods = false;
                    this.$message({
                        message: "操作成功",
                        showClose: true,
                        customClass: 'success'
                    });
                    //
                    let body = res.data;
                    this.choiceArr = body.items;
                    this.totalPrice = {
                        count: body.count, // 总数量
                        total: body.total, // 总计金额
                        discount: body.discount, // 优惠金额
                        amount: body.amount, // 最终价格
                        removeZero: body.removeZero, // 最终价格
                    }
                    this.addGoodBtn = true;
                    // 
                    setTimeout(()=>{
                        this.canClick = true;
                    },1000);
                    // this.returnMoney(false);
                }).catch(err=>{
                    setTimeout(()=>{
                        this.canClick = true;
                    },1000);
                })
            }
        },
        doShowPeiGoods(item){
            this.nowSelNeedPeiItem = item;
            this.nowSelPeiGoodsIds = [];
            this.nowSelPeiGoods = [];
            if(item.masterItemDtos && Array.isArray(item.masterItemDtos) && item.masterItemDtos.length){
                let nowSelPeiGoodsIds = [];
                let masterItemDtos = JSON.parse(JSON.stringify(item.masterItemDtos));
                let obj = {};
                masterItemDtos.forEach(it=>{
                    obj[it.productId] = it;
                    nowSelPeiGoodsIds.push(it.productId);
                });
                let tempArr = [];
                for(let k in obj){
                    obj[k]["id"] =  obj[k].productId;
                    tempArr.push(obj[k]);
                }
                this.nowSelPeiGoodsIds = nowSelPeiGoodsIds;
                this.nowSelPeiGoods = tempArr;
            }
            this.$http({
                url:"match/product/list",
                method:"POST",
                data:{
                    productId:item.productId
                }
            }).then(res=>{
                if(res.data && Array.isArray(res.data) && res.data.length){
                    res.data.forEach(it=>{
                        it.selCount = 0;
                    })
                    this.peiGoods = res.data;
                    this.showPeiGoods = true;
                }else{
                    this.$message({
                        message: "暂无相关配品，请在后台设置。",
                        customClass: 'error'
                    });
                    return;
                }
            })
        },
        //   
        spliceStr(str){
            return str.substring(0,9) + "...";
        },
        returnMoney(){
            this.$http({
                url:API_BASE_URL+"v1/pos/return-order",
                method:"POST",
                data:{
                    orderId:this.orderId
                }
            }).then(res=>{
                console.log(res);
                if(res.data.result.code == 200){
                    let body = res.data.data;
                    this.choiceArr = body.items;
                    this.totalPrice = {
                        count:    body.count, // 总数量
                        total:    body.total, // 总计金额
                        discount: body.discount, // 优惠金额
                        amount:   body.amount, // 最终价格
                        removeZero:   body.removeZero, // 最终价格
                    }
                    this.showPayBox=false;
                }else if(res.data.result.code == 400){
                    this.createOrder();
                }
            });
        },
        //   
        wipeZero(){
            if(!sessionStorage.getItem("orderId")){
                this.$message({
                    message: "暂无订单",
                    customClass: 'error'
                });
                return;
            }
            if(Number(this.wipeZeroMoney) > this.totalPrice.amount.toFixed(2)){
                this.wipeZeroMoney = this.totalPrice.amount.toFixed(2);
            }
            let amount = this.wipeZeroMoney;
            console.log(amount);
            this.$http({
                url:API_BASE_URL+"v1/pos/remove-zero",
                method:"POST",
                data:{
                    orderId:this.orderId,
                    amount
                }
            }).then(res=>{
                if(res.data.result.code == 400){
                    this.$message({
                        message: res.data.result.msg,
                        showClose: true,
                        customClass: 'error'
                    });
                    return; 
                }else if(res.data.result.code == 200){
                    this.$message({
                        message: res.data.result.msg,
                        customClass: 'success'
                    });
                    this.showSetWrap = false;
                    this.showAlertPwd = false;
                    this.disCountPwd = "";

                    let body = res.data.data;
                    this.choiceArr = body.items;
                    this.totalPrice = {
                        count:    body.count, // 总数量
                        total:    body.total, // 总计金额
                        discount: body.discount, // 优惠金额
                        amount:   body.amount, // 最终价格
                        removeZero:   body.removeZero, // 最终价格
                    }
                    this.checkedWipeZero = false;
                }
            })
        },
        showPwd(){
            if(this.showSetWrap){
                return;
            }
            this.showAlertPwd=true;
            // this.showSetWrap=true;
        },
        checkDiscountPwd(){
            if(!this.disCountPwd){
               this.$message({
                    message: "请输入密码",
                    customClass: 'error'
                });
                return; 
            }
            let pwd = new Base64();
            let pwdStr = 'hxbs 123.999'+ pwd.encode(this.disCountPwd);
            this.$http({
                url:API_BASE_URL+"v1/pos/judge-psw",
                method:"POST",
                data:{
                    storeId:this.storeId,
                    judgePsw:pwdStr
                }
            }).then(res=>{
                if(res.data.code == 400){
                    this.$message({
                        message: res.data.msg,
                        customClass: 'error'
                    });
                    return; 
                }else if(res.data.code == 200){
                    this.showSetWrap = true;
                    this.showAlertPwd = false;
                    this.disCountPwd = "";
                }
            })
        },
        //打折
          discountThisOrder(){
            if(!sessionStorage.getItem("orderId")){
                this.$message({
                    message: "暂无订单",
                    customClass: 'error'
                });
                return;
            }

            this.$http({
                url:API_BASE_URL+"v1/pos/return-order",
                method:"POST",
                data:{
                    orderId:this.orderId
                }
            }).then(res=>{
                console.log(res);
                if(res.data.result.code == 200){
                    let body = res.data.data;
                    this.choiceArr = body.items;
                    this.totalPrice = {
                        count:    body.count, // 总数量
                        total:    body.total, // 总计金额
                        discount: body.discount, // 优惠金额
                        amount:   body.amount, // 最终价格
                        removeZero:   body.removeZero, // 最终价格
                    }

                    // 
                    
                    if(this.firstDiscount == 0 && this.lastDiscount == 0){
                        if(this.wipeZeroMoney != ''){
                            if(!/^(0|[1-9][0-9]{0,9})(\.[0-9]{1,2})?$/.test(this.wipeZeroMoney)){
                                this.$message({
                                    message: "输入错误",
                                    showClose: true,
                                    customClass: 'error'
                                });
                                return;
                            }
                            this.wipeZero();
                        }
                        this.showSetWrap = false;
                        return; 
                    }
                    this.orderId = sessionStorage.getItem('orderId');
                    let percent = parseFloat((`${this.firstDiscount}${this.lastDiscount}`)/100);
                    this.$http({
                        url:API_BASE_URL+"v1/pos/discount",
                        method:"POST",
                        data:{
                            orderId:this.orderId,
                            percent
                        }
                    }).then(res=>{
                        if(res.data.result.code == 400){
                            this.$message({
                                message: res.data.result.msg,
                                customClass: 'error'
                            });
                            return; 
                        }else if(res.data.result.code == 200){
                            this.$message({
                                message: res.data.result.msg,
                                customClass: 'error'
                            });
                            this.showSetWrap = false;
                            this.showAlertPwd = false;
                            this.disCountPwd = "";

                            let body = res.data.data;
                            this.choiceArr = body.items;
                            this.totalPrice = {
                                count:    body.count, // 总数量
                                total:    body.total, // 总计金额
                                discount: body.discount, // 优惠金额
                                amount:   body.amount, // 最终价格
                                removeZero:   body.removeZero, // 最终价格
                            }
                            if(this.wipeZeroMoney != ''){
                                if(!/^(0|[1-9][0-9]{0,9})(\.[0-9]{1,2})?$/.test(this.wipeZeroMoney)){
                                    this.$message({
                                        message: "输入错误",
                                        showClose: true,
                                        customClass: 'error'
                                    });
                                    return;
                                }
                                this.wipeZero();
                            }
                        }
                    })
                    // 
                }else if(res.data.result.code == 400){
                    this.createOrder();
                }
            });

        },
        //   
        goVipCharge(){
            this.showRecharge=true;
            this.showPayBox=false;
            // this.$createScroll('recharge');
        },
        chargePay(){
           let _this = this;
            this.canDeletepayment = false;
            wx.scanQRCode({
                needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                success: function (res) {
                    var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                    var resultArr = result.split(",");
                    // 支付
                    _this.payCode = resultArr[resultArr.length-1];
                    // _this.showPayLoding = true;
                    _this.showPayBox = false;
                    if(result === 'scan resultStr is here'||_this.payCode === ''||result===''){
                        _this.$message({
                            message: '支付失败，请重新扫描。',
                            customClass: 'error'
                        })
                        _this.showPayLoding = false;
                        return;
                    }
                    let data = {
                        "orderId": _this.curVipChargeInfo.id,
                        "channel": "PAYCARD",
                        "amount": _this.curVipChargeInfo.amount,
                        "authCode": _this.payCode,
                        "notes": "会员充值"
                    }
                    
                    _this.$http.put(API_BASE_URL+'v1/clerk/scanPayments/' + _this.$uuid(), data).then((res)=>{
                        _this.payCode = '';
                        if ( res.status === 202 ) {
                            let overTimeNum = 0;
                            let curOrderId = _this.curVipChargeInfo.id;

                            // _this.delPaymentLodingTimer();
                            _this.payLoadTimer = setInterval(()=>{
                                overTimeNum += 2;
                                if ( overTimeNum >= 180 ) { // 超过180秒，取消订单
                                    clearInterval(_this.payLoadTimer);
                                    // _this.createOrder();
                                    return;
                                }
                                // let that = _this;
                                _this.payLoad(curOrderId, function () {
                                    clearInterval(_this.payLoadTimer);

                                    // _this.createOrder();
                                    _this.showPayLoding = false;
                                    // _this.$router.push({path:'/buySuccess/'+sendOrderId});//跳转购买成功页面
                                    _this.$message({
                                        message: '充值成功',
                                        customClass: 'success'
                                    });
                                    _this.getMemberData(_this.vipData.memberId);
                                    _this.showChargeType = false;
                                    _this.showRecharge = false;
                                    _this.inputVipMoney = "";
                                });
                            }, 2000)
                        } else {
                            
                            // _this.$router.push({path:'/buySuccess/'+sendOrderId});//跳转购买成功页面
                            _this.$message({
                                message: '充值成功',
                                customClass: 'success'
                            });
                            _this.getMemberData(_this.vipData.memberId);
                            _this.showChargeType = false;
                            _this.showRecharge = false;
                            _this.inputVipMoney = "";
                            // _this.createOrder();
                        
                        }
                    }).catch((err)=>{
                        _this.payCode = '';
                        _this.showPayLoding = false;
                        if ( err.response.status === 400 ) {
                            _this.showPayBox = true;
                        }
                    })
                    // 支付结束
                },
                fail:function(res){
                    _this.$message({
                        message: res,
                        showClose: true,
                        customClass: 'error'
                    });
                    return;
                }
            });
        },
        // 获取会员信息
        getMemberData: function ( memberId ) {
            this.$http.get(API_BASE_URL+"v1/pos/"+this.storeId+'/members?memberId='+memberId).then((res)=>{
                // this.vipData = res.data;
                this.vipData.amount = res.data.amount.toFixed(2);
            });
        },
        chargeVip(item){
            console.log(this.inputVipMoney)

            if(item){
                this.inputVipMoney = "";
            }else{
                if(!/^(0|[1-9][0-9]{0,9})(\.[0-9]{1,2})?$/.test(this.inputVipMoney)|| this.inputVipMoney == 0){
                    this.$message({
                        message: '充值金额输入有误',
                        showClose: true,
                        customClass: 'error'
                    });
                    return;
                }
                let rechargeLimit = JSON.parse(localStorage.getItem("rechargeLimit"));
                if(Number(this.inputVipMoney)<Number(rechargeLimit)){
                    this.$message({
                        message: '充值金额不能小于'+Number(rechargeLimit)+'元',
                        showClose: true,
                        customClass: 'error'
                    });
                    return;
                }
            }
            this.$http({
                url:API_BASE_URL+"v1/clerk/member-charges/"+this.$uuid(),
                method:"PUT",
                data:{
                    "storeId": this.storeId,
                    "memberId": this.vipData.memberId,
                    "amount": parseFloat(this.inputVipMoney?this.inputVipMoney:item.depositAmount),
                    "chargeRuleId": this.inputVipMoney?'':item.id,
                    "type":"CLERK"
                }
            }).then(res=>{
                this.curVipChargeInfo = res.data;
                this.showChargeType = true;
                console.log(res);
            })
        },
        testPay(){
            this.showPayLoding = true;
            this.showPayBox = false;
            this.showTestPayCode = true;
            let data = {
                        "orderId": this.orderId,
                        "channel": this.payType,
                        "amount": this.totalPrice.amount,
                        "authCode": this.testPayCode,
                        "tableNo": this.tableNo,
                        "notes": this.notes
                    }
                    let sendOrderId = this.orderId;
                    // if ( this.totalPrice.count <= 0 && this.totalPrice.total <= 0 ) {
                    //     return;
                    // }
                    this.$http.put(API_BASE_URL+'v1/clerk/scanPayments/' + this.$uuid(), data).then((res)=>{
                        this.testPayCode = '';
                        if ( res.status === 202 ) {
                            let overTimeNum = 0;
                            let curOrderId = this.orderId;

                            this.delPaymentLodingTimer();
                            this.payLoadTimer = setInterval(()=>{
                                overTimeNum += 2;
                                if ( overTimeNum >= 180 ) { // 超过180秒，取消订单
                                    clearInterval(this.payLoadTimer);
                                    // this.createOrder();
                                    return;
                                }
                                // let that = _this;
                                this.payLoad(curOrderId,()=> {
                                    clearInterval(this.payLoadTimer);

                                    this.createOrder();
                                    this.showPayLoding = false;
                                    this.$router.push({path:'/buySuccess/'+sendOrderId});//跳转购买成功页面
                                });
                            }, 2000)
                        } else {
                            
                            this.$router.push({path:'/buySuccess/'+sendOrderId});//跳转购买成功页面

                            this.createOrder();
                        
                        }
                    }).catch((err)=>{
                        this.testPayCode = '';
                        this.showPayLoding = false;
                        if ( err.response.status === 400 ) {
                            // this.showPayBox = true;
                            // this.searchOrderType();
                        }
                    });
        },
 
        //   扫一扫
        scanCode(){
            let _this = this;
            this.canDeletepayment = false;
            wx.scanQRCode({
                needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                success: function (res) {
                    var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                    var resultArr = result.split(",");
                    // 支付
                    _this.payCode = resultArr[resultArr.length-1];
                    _this.showPayLoding = true;
                    _this.showPayBox = false;
                    if(result === 'scan resultStr is here'||_this.payCode === ''||result===''){
                        _this.$message({
                            message: '支付失败，请重新扫描。',
                            customClass: 'error'
                        })
                        _this.showPayLoding = false;
                        return;
                    }
                    // 过滤错误的支付码
                    if(!_this.payCode || String(_this.payCode).trim().length < 18){
                        _this.$message({
                            message: '付款码不全，请重新扫码',
                            customClass: 'error',
                            duration:5900,
                        })
                        _this.showPayLoding = false;
                        return;
                    }
                    let data = {
                        "orderId": _this.orderId,
                        "channel": _this.payType,
                        "amount": _this.totalPrice.amount,
                        "authCode": _this.payCode,
                        "tableNo": _this.tableNo,
                        "notes": _this.notes
                    }
                    if(_this.nowSelCoupon && _this.nowSelCoupon.code && _this.isBindCoupon){
                        data = Object.assign(data,{
                            coupon:[
                                {
                                    couponInstanceCode:_this.nowSelCoupon.code
                                }
                            ]
                        })
                    }
                    let sendOrderId = _this.orderId;
                    if ( _this.totalPrice.count <= 0 && _this.totalPrice.total <= 0 ) {
                        return;
                    }
                    _this.$http.put(API_BASE_URL+'v1/clerk/scanPayments/' + _this.$uuid(), data).then((res)=>{
                        _this.payCode = '';
                        if ( res.status === 202 ) {
                            let overTimeNum = 0;
                            let curOrderId = _this.orderId;

                            _this.delPaymentLodingTimer();
                            _this.payLoadTimer = setInterval(()=>{
                                overTimeNum += 2;
                                if ( overTimeNum >= 180 ) { // 超过180秒，取消订单
                                    clearInterval(_this.payLoadTimer);
                                    _this.createOrder();
                                    return;
                                }
                                // let that = _this;
                                _this.payLoad(curOrderId, function () {
                                    clearInterval(_this.payLoadTimer);

                                    _this.createOrder();
                                    _this.showPayLoding = false;
                                    _this.$router.push({path:'/buySuccess/'+sendOrderId});//跳转购买成功页面
                                });
                            }, 2000)
                        } else {
                            
                            _this.$router.push({path:'/buySuccess/'+sendOrderId});//跳转购买成功页面

                            _this.createOrder();
                        
                        }
                    }).catch((err)=>{
                        // window.location.reload(true);
                        if ( err.response.status === 400 ) {
                            // _this.showPayBox = true;
                            // _this.searchOrderType();
                            // return;
                        }
                        _this.payCode = '';
                        _this.showPayLoding = false;
                        // _this.showPayErr = true;
                        // 
                        let tipText;
                        err.response.data.message?tipText=err.response.data.message:tipText=err.response.data;
                        _this.errMsg = tipText;
                    })
                    // 支付结束
                },
                fail:function(res){
                    _this.$message({
                        message: '网络有误，请检查本地网络',
                        showClose: true,
                        customClass: 'error'
                    });
                    return;
                }
            });
        },
        delPaymentLodingTimer: function () {
            setTimeout(()=>{
                this.delPaymentLodingTime--;
                if ( this.delPaymentLodingTime <= 0 ) {
                    this.canDeletepayment = true;
                    this.delPaymentLodingTime = 30;
                } else {
                    this.delPaymentLodingTimer();
                }
            },1000)
        },
        // 等待支付轮训接口
        payLoad: function ( orderId, fn ) {
            this.$http.get(API_BASE_URL+'v1/pay/micropay/query?orderId='+orderId).then((res)=>{
                if ( res.status === 200 ) {
                    fn();
                }else if(res.status === 400 || res.status === 500){
                    this.showPayBox = true;
                    this.payApiBtn = true;
                    this.paymentBtn = true;
                    this.showPayLoding = false;
                    clearInterval(this.payLoadTimer);
                }
            }).catch(( err )=>{
                // this.showPayBox = true;
                // this.payApiBtn = true;
                // this.paymentBtn = true;
                this.showPayLoding = false;
                // window.location.reload(true);
                // this.showPayErr = true;
                let tipText;
                err.response.data.message?tipText=err.response.data.message:tipText=err.response.data;
                this.errMsg = tipText;
                clearInterval(this.payLoadTimer);
            })
        },
         // 查询订单状态
        searchOrderType: function () {
            this.$http.get(API_BASE_URL+'v1/pos/orders/' + this.orderId).then((res)=>{
                if ( this.newOrderStatus[res.data.status] ) {
                    // this.createOrder();
                }
            });
        },
        //取消支付
        deletePayment( orderId ){
            if ( !this.canDeletepayment ) {
                return;
            } else {
                this.paymentBtn=true;
                clearInterval(this.payLoadTimer);

                if ( !this.delPaymentApiBtn ) {
                    return;
                }
                this.delPaymentApiBtn = false;
                this.$http.delete(API_BASE_URL+'v1/pos/payments/'+orderId).then((res)=>{
                    this.showPayLoding = false;
                    this.delPaymentApiBtn = true;
                    // this.createOrder();
                    this.showCancelInfo = true;
                }).catch(()=>{
                    this.showPayLoding = false;
                    this.delPaymentApiBtn = true;
                })
            }
        },
        //   显示商品图片信息
        showImg(imgInfo){
            console.log(imgInfo)
            if(imgInfo){
                this.nowImg = imgInfo;
            }
        },
        hideImg(){
            this.nowImg = '';
        },
        //输入手机号
        showEnterPhoneFn(){
            this.EnterPhone = this.EnterPhone.replace(/\s+/g,'') 
            if ( this.EnterPhone.length<4 ) {
                this.$message.error({
                    message: "手机号至少4位",
                    customClass: 'error',
                });
                return;
            }
            this.$http.get(API_BASE_URL+'v1/member/members-search?storeId='+this.storeId+'&q='+this.EnterPhone).then((res)=>{
                for (var i = 0; i < res.data.length; i++) {
                    res.data[i].amount = res.data[i].amount.toFixed(2);
                }
                // if ( res.data.length == 1 ) {
                //     this.selPhoneVip(res.data[0]);
                // } else {
                // }
                this.vipPhoneList = res.data;
            })
        },
        // 选择会员
        selPhoneVip: function ( vipItem ) {
            this.$http.put('orders/'+this.orderId+'/attachMember?memberId='+vipItem.memberId).then((res)=>{
                this.closeVipCode();
                this.vipData = vipItem;
                this.$message({
                    message: '成功绑定会员',
                    customClass: 'success'
                });
                let body = res.data;
                this.choiceArr = body.items;
                this.totalPrice = {
                    count: body.count, // 总数量
                    total: body.total, // 总计金额
                    discount: body.discount, // 优惠金额
                    amount: body.amount, // 最终价格
                    removeZero:body.removeZero,
                }
            })
        },
        // 收缩展开商品分类
        traggerType( evnet ) {
            console.log("l;l")
            if ( $(event.target).parent().css('height') == '1rem' ) {
                $(event.target).parent().css('height', 'auto');
            } else {
                $(event.target).parent().css('height', '1rem');
            }
            try {
                // setTimeout(()=>{
                    // this.goodsListScroll.refresh();
                    // this.right_goodsScroll.refresh();
                    // this.left_barScroll.refresh();
                // },1500)
            } catch (error) {
                
            }
            
            // setTimeout(function () {
            //     this.goodsListScroll.refresh();
            //     this.right_goodsScroll.refresh();
            //     this.left_barScroll.refresh();
            // }, 100);
            
            // myScroll.refresh();
            // this.$nextTick(()=>{
            //     this.$createScroll('goodsList');
            //     this.$createScroll('right_goods');
            //     this.$createScroll('left_bar');
            //     this.$createScroll('carGoodsBox');
            // })
        },
        openNumberBox: function ( productId ) {
            this.showNumBox = true;
            this.curProductId = productId;
            this.goodNumber = '';
        },
        clickNum: function ( num ) {
            if ( !this.goodNumber && num == '0' ) {
                return;
            }
            if ( this.goodNumber.length >= 4 ) {
                return;
            }
            this.goodNumber += num;
        },
        delNumber: function () {
            this.goodNumber = this.goodNumber.substring(0, this.goodNumber.length-1);
        },
        saveNumber: function () {
            if ( !this.goodNumber ) {
                return;
            }
            this.addProduct(this.curProductId, true, parseInt(this.goodNumber),false,null);
            this.showNumBox = false;
        },
        clickInput: function ( event ) {
        },
  		// 点击选好了触发
  		goPayType: function () {
            if(!this.choiceArr.length){
                this.$message({
                    message: "亲，请选择商品",
                    customClass: 'error'
                });
                return;
            }
            this.showEnterPhone = true;
            this.EnterPhone = '';
            
            //不要会员添加
            this.showPayBox = true;
            return;

            // this.$http.get('query-binding?orderId='+this.orderId+'&type=CHECK').then((res)=>{
            //     if ( res.data.url ) {
            //         this.isqrcode = true;
            //         this.clerkMemberSwitch = !res.data.clerkMemberSwitch;
            //         setTimeout(()=>{
            //             $('#vipQrcode')[0].innerHTML='';
            //             let vipQrcode = new QRCode("vipQrcode", {
            //                 text: res.data.url,
            //                 colorDark : "#000000",
            //                 colorLight : "#ffffff",
            //                 height: 200,
            //                 width: 200,
            //                 correctLevel : QRCode.CorrectLevel.H
            //             });
            //         },200)
            //         this.vipLoginTimer = setInterval(()=>{
            //             this.vipLoginQuery(true);
            //         },2000)
            //     } else {
          	// 		this.showCarDetail = false;
          	// 		this.choiceArr.length>0?this.showPayBox=true:null;
            //     }
            // }).catch((err)=>{
            // });
          },
        showBindVipBoxOrPayByVip(){
            if(!this.vipData){
                this.$http.get('query-binding?orderId='+this.orderId+'&type=CHECK').then((res)=>{
                    if ( res.data.url ) {
                        this.isqrcode = true;
                        this.clerkMemberSwitch = !res.data.clerkMemberSwitch;
                        setTimeout(()=>{
                            $('#vipQrcode')[0].innerHTML='';
                            let vipQrcode = new QRCode("vipQrcode", {
                                text: res.data.url,
                                colorDark : "#000000",
                                colorLight : "#ffffff",
                                height: 200,
                                width: 200,
                                correctLevel : QRCode.CorrectLevel.H
                            });
                        },200)
                        this.vipLoginTimer = setInterval(()=>{
                            this.vipLoginQuery(true);
                        },2000)
                    } else {
                        this.showCarDetail = false;
                        this.choiceArr.length>0?this.showPayBox=true:null;
                    }
                }).catch((err)=>{
                });
            }else{
                this.payByType('MEMBER');
            }
            
        },
  		// 切换商品分类
  		changeGoodType: function ( index ) {
  			this.curIdx = index;
  			let that = this;
  			setTimeout(()=>{
                $('.goods_item').css('height','1rem');
                $('.goods_item.oneLevel').css('height','auto');
                $('.goods_item:nth-of-type(2)').css('height','auto');
  				$('.goods_item .changeNumber .addNumber').bind('moveAnimate', function ( e, curDom ) {
  					that.animateDom.css("left", $(curDom).offset().left + "px");
  					that.animateDom.css("top", $(curDom).offset().top  + "px");
  					that.shoppingCartAnimate();
  				})

                Echo.init({
                    offset: 0,//离可视区域多少像素的图片可以被加载
                　　throttle: 0, //图片延时多少毫秒加载
                    scrollDomId: 'right_goods',
                });
            });
            // setTimeout(()=>{
                // this.goodsListScroll.refresh();
                // this.right_goodsScroll.refresh();
                // this.left_barScroll.refresh();
            // },1500)
  		},
  		// 点击现金支付
  		placeOrder: function () {
            if ( !this.clerkCashSales ) {
                this.$message({
                    message: "不支持现金支付",
                    customClass: 'error'
                });
                return;
            }

            if ( !this.payBtn ) {
                return;
            }
            this.payBtn = false;

			// 生成订单
            let sendOrderId = this.orderId;

            this.curPaymentId = this.$uuid();
            let data = {
                "orderId": this.orderId,
                "channel": 'CASH',
                "amount": this.totalPrice.amount,
                "tableNo": this.tableNo,
                "notes": this.notes
            }
            if(this.nowSelCoupon && this.nowSelCoupon.code && this.isBindCoupon){
                data = Object.assign(data,{
                    coupon:[
                        {
                            couponInstanceCode:this.nowSelCoupon.code
                        }
                    ]
                })
            }
            clearInterval(this.intervalTimer);
            this.$http.put('payments/' + this.curPaymentId, data).then((res)=>{ // 支付
                this.showPayBox = false;
                this.payBtn = true;
                // 生成新订单
                this.createOrder();
                this.$router.push({path:'/buySuccess/'+sendOrderId});//跳转购买成功页面
            }).catch(()=>{
                this.payBtn = true;
            })
  		},
  		// 通过支付宝支付
  		payByType: function ( payType ) {
            let oldOrderId = this.orderId; // 缓存订单id

            // 判断当前是否正在请求
            if ( !this.payBtn ) {
                return;
            }
            this.payBtn = false;

            this.curPaymentId = this.$uuid();
            let data = {
                "orderId": this.orderId,
                "channel": payType,
                "amount": this.totalPrice.amount,
                "tableNo": this.tableNo,
                "notes": this.notes
            }
            if(this.nowSelCoupon && this.nowSelCoupon.code && this.isBindCoupon){
                data = Object.assign(data,{
                    coupon:[
                        {
                            couponInstanceCode:this.nowSelCoupon.code
                        }
                    ]
                })
            }
            
            clearInterval(this.intervalTimer);
            clearInterval(this.timeDownTimer);
            
            if(payType=='alipay'){
                this.payByAlipayOrWechat( true, oldOrderId );
                return;
            }
            if(payType=='wechat'){
                this.payByAlipayOrWechat( false, oldOrderId );
                return;
            }
            this.$http.put('payments/' + this.curPaymentId, data).then((res)=>{
                this.createOrder();
                this.payBtn = true;
                this.$router.push({path:'/buySuccess/'+oldOrderId});//跳转购买成功页面
            }).catch((res)=>{
                this.payBtn = true;
            });
  		},
        //倒计时 3min;
        timeDownFn(){
            let m=2,s=59;
            this.timeDownTimer = setInterval(()=>{
                s--;
                if(s==-1&&m==0){
                    clearInterval(this.timeDownTimer);
                    clearInterval(this.intervalTimer);
                    this.showCode = false;
                    this.canclePayment();
                    this.timeDown ='0:00'
                }else{
                    if(s==-1){
                        s = 59;
                        m--;
                    };
                    this.timeDown = m+':'+(s<10?('0'+s):s);
                }
            },1000)
        },
        // 二维码支付成功
        payOfflineSuccess: function ( channel ) {
            if ( !this.offlinePayType ) {
                return;
            }
            if ( !this.payBtn ) {
                return;
            }
            this.payBtn = false;

            this.curPaymentId = this.$uuid();
            let oldOrderId = this.orderId; // 缓存订单id
            
            this.$http.put('payments/' + this.curPaymentId, {
                "orderId": this.orderId,
                "channel": this.offlinePayType,
                "amount": this.totalPrice.amount,
                "tableNo": this.tableNo,
                "notes": this.notes
            }).then((res)=>{
                this.createOrder();
                this.payBtn = true;
                this.$router.push({path:'/buySuccess/'+oldOrderId});//跳转购买成功页面
            }).catch((res)=>{
                this.payBtn = true;
            });
        },
        // 通过支付宝或微信支付
        payByAlipayOrWechat: function ( boo, oldOrderId ) {
            this.$http.post(API_BASE_URL+'v1/pay/scan-code',{
                "orderId": oldOrderId,
                "type": boo,
                "tableNo": this.tableNo,
                "notes": this.notes
            }).then((res)=>{
                this.payImgUrl = res.data.url;
                this.showCode = true;
                this.payBtn = true;

                if ( res.data.payMode == 'CASHIER' ) {
                    this.isOnline = false;
                    boo?this.offlinePayType='ALIPAY_CASH':this.offlinePayType='WECHATPAY_CASH';
                    return;
                } else {
                    this.isOnline = true;
                }

                this.timeDown = '2:59';
                this.timeDownFn();
                this.intervalTimer = setInterval(()=>{
                    this.$http.get(API_BASE_URL+'v1/pay/scan-code/query?orderId='+oldOrderId).then((res)=>{
                        if ( res.status === 200 ) {
                            clearInterval(this.intervalTimer);
                            clearInterval(this.timeDownTimer);
                            this.createOrder();
                            this.$router.push({path:'/buySuccess/'+oldOrderId});//跳转购买成功页面
                            this.showPayBox = false;
                        }
                    }).catch(()=>{
                        clearInterval(this.intervalTimer);
                        clearInterval(this.timeDownTimer);
                        this.showPayBox = false;
                        this.showCode = false;
                        this.showDelConfirm = false;
                    })
                }, 2000)
            }).catch(()=>{
                this.payBtn = true;
            })
        },
        // 关闭二维码框
        closeCodeImg: function () {
            if ( this.isOnline ) {
                this.showDelConfirm = true;
            } else {
                this.showCode = false;
            }
        },
  		// 获取商品列表
  		getGoods(){
            if ( !this.storeId ) {
                return;
            }
			this.$http.get('products?storeId='+ this.storeId).then((res)=>{
                let rentCates = [];
                let normalCates = [];
                if(res.data && Array.isArray(res.data) && res.data.length){
                    // 
                    res.data.forEach((it,ind)=>{
                        // 
                        if(it.leaseEnabled){
                            if(it.products && Array.isArray(it.products) && it.products.length){
                                it.products.forEach(ite=>{
                                    ite.productStatus = "ON";
                                    ite.leaseEnabled = true;
                                })
                            }
                            rentCates.push(it);
                        }else{
                            normalCates.push(it);
                        }
                    })
                    // 
                    normalCates.forEach(it=>{
                        if(it.subTypes && Array.isArray(it.subTypes) && it.subTypes.length){
                            let subTypes = JSON.parse(JSON.stringify(it.subTypes));
                            subTypes.sort((a,b)=>{
                                return a.sequence - b.sequence;
                            });
                            it.subTypes = subTypes;
                        }
                    })
                    
                }
                // this.goodsData = res.data;
                if(this.leaseProductEnabled){
                    this.goodsData = [...normalCates,...rentCates];
                }else{
                    this.goodsData = [...normalCates];
                }
                let that = this;
                setTimeout(()=>{
                	$('.goods_item .changeNumber .addNumber').bind('moveAnimate', function ( e, curDom ) {
                		that.animateDom.css("left", $(curDom).offset().left + "px");
                		that.animateDom.css("top", $(curDom).offset().top  + "px");
                		that.shoppingCartAnimate();
                	})

                    Echo.init({
                        offset: 0,//离可视区域多少像素的图片可以被加载
                    　　throttle: 0, //图片延时多少毫秒加载
                        scrollDomId: 'right_goods',
                    });
                });
			})
  		},
  		// 购物车动画
  		shoppingCartAnimate(){
            var flyElm = this.animateDom.clone();
            $('.takeOrder').append(flyElm);
            flyElm.css({
            	'zIndex': 99,
                'top': this.animateDom.offset().top +'px',
                'left': this.animateDom.offset().left +'px',
            });
            flyElm.animate({
                top: this.carDom.offset().top,
                left: this.carDom.offset().left,
                width: 10,
                height: 10
            }, 'slow', function() {
                flyElm.remove();
            });
        },
        beforeSelGoods(item){
            console.log(item);
            // 
            if(item.hasOwnProperty("leaseEnabled") && item.leaseEnabled){
                this.showRentInfo = true;
                if(item.extras && Array.isArray(item.extras) && item.extras.length){
                    item.extras.forEach((it,ind)=>{
                        if(typeof it == "string"){
                            item.extras[ind] = JSON.parse(it);
                        }
                    })
                    this.nowSelRentGoodsRules = item.extras;
                    this.nowSelRentGoodsRules.forEach((it,ind)=>{
						if(it.defaultPcRule){
							this.rentForm.ruleId = it.ruleId;
							this.nowSelRentRule  = it;
						}
					})
                    try {
                        let rentInfo = localStorage.getItem("rentInfo");
                        
                        if(rentInfo){
                            rentInfo = JSON.parse(rentInfo);
                            if(rentInfo.hasOwnProperty("areaId")){
                                this.rentForm.areaId = rentInfo.areaId;
                                this.rentForm.numId = rentInfo.numId;
                                // 
                                if(this.areas && Array.isArray(this.areas)){
                                    this.areas.forEach(it=>{
                                        if(it.id == this.rentForm.areaId){
                                            this.tables = it.nums;
                                            if(it.nums && Array.isArray(it.nums) && it.nums.length){
                                                this.tables.forEach(ite=>{
                                                    if(ite.id == this.rentForm.numId){
                                                        this.rentForm.numName = ite.name;
                                                    }
                                                })
                                            }
                                        }
                                    })
                                }
                                // 
                            }
                        }
                    } catch (error) {
                        
                    }
                    try {
                        let rentMobile = localStorage.getItem("rentMobile");
                        if(rentMobile){
                            rentMobile = JSON.parse(rentMobile)
                            if(rentMobile.hasOwnProperty("time") && rentMobile.hasOwnProperty("rentMobile")){
                                if((new Date().getTime() - new Date(rentMobile.time).getTime()) < 5 * 1000 * 60){
                                    this.rentForm.mobile = rentMobile.rentMobile;
                                }
                            }
                        }
                    } catch (error) {
                        
                    }
                }
                console.log(item);
                this.nowSelRentGoods = item;
                this.rentForm.productId = item.id;
                // 
                let employeeName = localStorage.getItem("employeeName");
                let empId = localStorage.getItem("empId");
                if(employeeName){
                    this.rentForm.empName = employeeName;
                }
                if(empId){
                    this.rentForm.empId = empId;
                }
                this.$forceUpdate();
                return;
            }
            // 
            if(item.stockEnabled&&!item.quantity){
				this.$message({
		        	message: '无货',
		        	customClass: 'error'
		        });
				return;
			}
			if(item.productSpecs && Array.isArray(item.productSpecs) && item.productSpecs.length){
                let resetFlag = true;
                let seledItem = null;
                if(this.choiceArr && Array.isArray(this.choiceArr) && this.choiceArr.length){
                    this.choiceArr.forEach(it=>{
                        if(it.productId == item.id){
                            resetFlag = false;
                            seledItem = it;
                        }
                    })
                }
                if(item.productSpecs && Array.isArray(item.productSpecs)){
                    if(resetFlag){
                        let nowSelSpec = [];
                        item.productSpecs.forEach(it=>{
                            it.seledSpec = it.defaultSpec;
                            nowSelSpec.push(it.defaultSpec);
                        })
                        this.nowSelSpec = nowSelSpec;
                    }else{
                        if(seledItem && seledItem.specs && Array.isArray(seledItem.specs)){
                            item.productSpecs.forEach(it=>{
                                if(it.specs && Array.isArray(it.specs)){
                                    it.specs.forEach(ite=>{
                                        if(seledItem.specs.indexOf(ite)!=-1){
                                            it.seledSpec = ite;
                                        }
                                    })
                                }
                            })
                          this.nowSelSpec = seledItem.specs;
                        }
                    }
                }
                this.specs = item.productSpecs;
                this.nowSelNeedSpecItem = item;
                this.showSelSpec = true;
                return
            }
			this.addProduct( item.id,true,null,false,item);
		},
  		// 添加商品
  		addProduct: function ( productId, btn, num ,ISmsg,item) {
            if(!this.canClick){
                // this.$message({
                //     message: "点击不能过快",
                //     showClose: true,
                //     duration:1000,
                //     customClass: 'error'
                // })
                return;
            }
            if ( productId == '0' && !num ) {
                return;
            }
            if ( !this.addGoodBtn ) {
                return;
            }
  			this.addGoodBtn = false;
            let data = {
                "productId": productId,
                "productCount": num?num:1,
                specs:this.fromSelSpec?this.nowSelSpec:undefined
            };
            if(item && Array.isArray(item.specs) && item.specs.length){
                data["specs"] = item.specs;
            }
            if ( productId == '0' ) {
                data = {
                    "productId": productId,
                    "productCount": 1,
                    "amount": num
                }
            }
            if(sessionStorage.getItem('orderId')){
                this.orderId = sessionStorage.getItem('orderId');
            }else{
                //没有就新建id
                let userName = localStorage.getItem("phone");
                let url='?createTime='+new Date().getTime()+'&storeId='+this.storeId+'&userName='+userName;

                this.$http.put('/create-orders'+url).then((res)=>{
                    sessionStorage.setItem('orderId',res.data.id);
                    this.orderId = res.data.id;
                    this.$http.post('orders/' + this.orderId + '/add', data).then((res)=>{
                        // 
                        try {
							let pId = `${this.nowSelSpec}_&_${productId}`;
							if(res.data.items && Array.isArray(res.data.items) && res.data.items.length){
								res.data.items.forEach(it=>{
									if((`${it.specs}_&_${it.productId}` == pId && it.matchEnabled) || (it.productId==productId && it.matchEnabled)){
										this.doShowPeiGoods(it);
									}
								})
							}
						} catch (error) {
							console.log(error);
						}
                        // 
                        this.fromSelSpec = false;
                        this.showSelSpec = false;
                        if ( btn ) {
                            $('#'+productId).trigger('moveAnimate', $('#'+productId));
                        }
                        if ( ISmsg ) {
                            this.$message({
                                message: "添加成功",
                                customClass: 'success'
                            });
                        }
                        let body = res.data;
                        this.choiceArr = body.items;
                        this.totalPrice = {
                            count: body.count, // 总数量
                            total: body.total, // 总计金额
                            discount: body.discount, // 优惠金额
                            amount: body.amount, // 最终价格
                            removeZero: body.removeZero, // 最终价格
                        }
                        this.addGoodBtn = true;
                    }).catch((err)=>{
                        this.fromSelSpec = false;
                        this.showSelSpec = false;
                        this.addGoodBtn = true;
                        if ( err.response.status === 400 ) {
                            this.$http.get('orders/' + this.orderId).then((res)=>{
                                if(!res.data.id){
                                    sessionStorage.removeItem("orderId");
                                    this.clearOrder();
                                    return;
                                }
                                if ( this.newOrderStatus[res.data.status] ) {
                                    sessionStorage.removeItem('orderId');
                                } else if ( res.data.status == 'NOTSURE' ) {
                                    // this.$router.push('/orderDetail/'+this.orderId);
                                    // this.showDelConfirm = true;
                                }
                            });
                        }
                    })
                })
                return;
            }
  		    this.$http.post('orders/' + this.orderId + '/add', data).then((res)=>{
                // 
                try {
                    let pId = `${this.nowSelSpec}_&_${productId}`;
                    if(res.data.items && Array.isArray(res.data.items) && res.data.items.length){
                        res.data.items.forEach(it=>{
                            if((`${it.specs}_&_${it.productId}` == pId && it.matchEnabled) || (it.productId==productId && it.matchEnabled)){
                                this.doShowPeiGoods(it);
                            }
                        })
                    }
                } catch (error) {
                    console.log(error);
                }
                // 
                this.fromSelSpec = false;
                this.showSelSpec = false;
                if ( btn ) {
      		        $('#'+productId).trigger('moveAnimate', $('#'+productId));
                }
  		        let body = res.data;
  		        this.choiceArr = body.items;
  		        this.totalPrice = {
  		            count: body.count, // 总数量
  		            total: body.total, // 总计金额
  		            discount: body.discount, // 优惠金额
  		            amount: body.amount, // 最终价格
  		            removeZero: body.removeZero, // 最终价格
  		        }
  		        this.addGoodBtn = true;
  		    }).catch((err)=>{
                this.fromSelSpec = false;
                this.showSelSpec = false;
  		    	this.addGoodBtn = true;
                if ( err.response.status === 400 ) {
                    this.$http.get('orders/' + this.orderId).then((res)=>{
                        if(!res.data.id){
                            sessionStorage.removeItem("orderId");
                            this.clearOrder();
                            return;
                        }
                        if ( this.newOrderStatus[res.data.status] ) {
                            // setTimeout(()=>{
                            //     this.$message({
                            //         message: "已重新生成订单",
                            //         customClass: 'error'
                            //     });
                            // }, 2000)
                            this.createOrder();
                        } else if ( res.data.status == 'NOTSURE' ) {
                            // this.$router.push('/orderDetail/'+this.orderId);
                            // this.showDelConfirm = true;
                        }
                    });
                }
              })
              this.canClick = false;
                setTimeout(()=>{
                    this.canClick = true;
                },500);
  		},
  		// 减少商品
  		reduceProduct: function ( productId ,item) {
              if(!this.canClick){
                // this.$message({
                //     message: "点击不能过快",
                //     showClose: true,
                //     duration:1000,
                //     customClass: 'error'
                // })
                return;
            }
  			if ( !this.reduceGoodBtn ) {
  				return;
  			}
            this.reduceGoodBtn = false;

            let data = {
                "productId": productId,
                "productCount": 1,
                specs:(item.specs&&Array.isArray(item.specs)&&item.specs.length)?item.specs:undefined
            };

  		    this.$http.post('orders/' + this.orderId + '/remove', data).then((res)=>{
  		        let body = res.data;
                if(body==''){
                    //订单已经删除
                    sessionStorage.removeItem('orderId');
                    this.orderId = '';
                    this.vipData = '';
                    this.choiceArr = [];
                    this.showCarDetail = false;
                    this.showPayBox = false;
                    this.totalPrice = {
                        count: 0, // 总数量
                        total: 0, // 总计金额
                        discount: 0, // 优惠金额
                        amount: 0, // 最终价格
                        removeZero: 0, // 最终价格
                    };
                    this.reduceGoodBtn = true;
                    return;
                }
  		        this.choiceArr = body.items;
  		        if ( this.choiceArr.length <= 0 ) {
  		        	this.showCarDetail = false;
  		        	this.showPayBox = false;
  		        }
  		        this.totalPrice = {
  		            count: body.count, // 总数量
  		            total: body.total, // 总计金额
  		            discount: body.discount, // 优惠金额
  		            amount: body.amount, // 最终价格
  		            removeZero: body.removeZero, // 最终价格
  		        }
  		        this.reduceGoodBtn = true;
  		    }).catch(()=>{
  		    	this.reduceGoodBtn = true;
                if ( err.response.status === 400 ) {
                    this.$http.get('orders/' + this.orderId).then((res)=>{
                        if(!res.data.id){
                            sessionStorage.removeItem("orderId");
                            this.clearOrder();
                            return;
                        }
                        if ( this.newOrderStatus[res.data.status] ) {
                            // setTimeout(()=>{
                            //     this.$message({
                            //         message: "已重新生成订单",
                            //         customClass: 'error'
                            //     });
                            // }, 2000)
                            this.createOrder();
                        } else if ( res.data.status == 'NOTSURE' ) {
                            // this.$router.push('/orderDetail/'+this.orderId);
                            // this.showDelConfirm = true;
                        }
                    });
                }
              })
              this.canClick = false;
                setTimeout(()=>{
                    this.canClick = true;
                },500);
  		},
  		// 改变动画位置
  		changeAnimate: function ( e ) {
  			this.animateDom.css("left", e.screenX + "px");
  			this.animateDom.css("top", e.screenY + "px");
  		},
        // 生成订单
        createOrder: function () {
            sessionStorage.removeItem('orderId');
            this.choiceArr = [];
            this.totalPrice = {
                count: 0, // 总数量
                total: 0, // 总计金额
                discount: 0, // 优惠金额
                amount: 0, // 最终价格
                removeZero: 0, // 最终价格
            }

            this.showPayBox = false;
            this.showCarDetail = false;
        },
        // 取消支付 （取消接口）
        canclePayment: function () {
            if ( !this.canclePaymentBtn ) {
                return;
            }
            this.canclePaymentBtn = false;

            clearInterval(this.intervalTimer);
            clearInterval(this.timeDownTimer);
            this.$http.delete('payments/'+this.orderId).then((res)=>{
                this.showDelConfirm = false;
                this.showCode = false;
                this.canclePaymentBtn = true;
            }).catch(( err )=>{
                this.showDelConfirm = false;
                this.showCode = false;
                this.canclePaymentBtn = true;
            })
        },
  		delOrder: function () {
  			this.$http.delete('orders/'+ this.orderId).then((res)=>{
                this.createOrder();
                this.$message({
                    message: "订单已取消",
                    customClass: 'error'
                });
                this.showDelConfirm = false;
  			})
  		},
        // vip登录时判断是否存在订单
        vipLoginCheckOrder: function () {
            console.log('121212')
            // if ( !this.orderId ) {
            //     let url='?createTime='+new Date().getTime()+'&storeId='+this.storeId;
            //     // 没有订单就创建订单
            //     this.$http.put('/create-orders'+url).then((res)=>{
            //         sessionStorage.setItem('orderId',res.data.id);
            //         this.orderId = res.data.id;
            //         this.getVipCode();
            //     })
            // } else {
            //     this.getVipCode();
            // }
        },
        //搜索并添加商品
        choiceProduct(item){
            // 
            if(item.hasOwnProperty("leaseEnabled") && item.leaseEnabled){
                this.showRentInfo = true;
                if(item.extras && Array.isArray(item.extras) && item.extras.length){
                    item.extras.forEach((it,ind)=>{
                        if(typeof it == "string"){
                            item.extras[ind] = JSON.parse(it);
                        }
                    })
                    this.nowSelRentGoodsRules = item.extras;
                    this.nowSelRentGoodsRules.forEach((it,ind)=>{
						if(it.defaultPcRule){
							this.rentForm.ruleId = it.ruleId;
							this.nowSelRentRule  = it;
						}
					})
                    try {
                        let rentInfo = localStorage.getItem("rentInfo");
                        
                        if(rentInfo){
                            rentInfo = JSON.parse(rentInfo);
                            if(rentInfo.hasOwnProperty("areaId")){
                                this.rentForm.areaId = rentInfo.areaId;
                                this.rentForm.numId = rentInfo.numId;
                                // 
                                if(this.areas && Array.isArray(this.areas)){
                                    this.areas.forEach(it=>{
                                        if(it.id == this.rentForm.areaId){
                                            this.tables = it.nums;
                                            if(it.nums && Array.isArray(it.nums) && it.nums.length){
                                                this.tables.forEach(ite=>{
                                                    if(ite.id == this.rentForm.numId){
                                                        this.rentForm.numName = ite.name;
                                                    }
                                                })
                                            }
                                        }
                                    })
                                }
                                // 
                            }
                        }
                    } catch (error) {
                        
                    }
                    try {
                        let rentMobile = localStorage.getItem("rentMobile");
                        if(rentMobile){
                            rentMobile = JSON.parse(rentMobile)
                            if(rentMobile.hasOwnProperty("time") && rentMobile.hasOwnProperty("rentMobile")){
                                if((new Date().getTime() - new Date(rentMobile.time).getTime()) < 5 * 1000 * 60){
                                    this.rentForm.mobile = rentMobile.rentMobile;
                                }
                            }
                        }
                    } catch (error) {
                        
                    }
                }
                console.log(item);
                this.nowSelRentGoods = item;
                this.rentForm.productId = item.id;
                // 
                let employeeName = localStorage.getItem("employeeName");
                let empId = localStorage.getItem("empId");
                if(employeeName){
                    this.rentForm.empName = employeeName;
                }
                if(empId){
                    this.rentForm.empId = empId;
                }
                return;
            }
            // 
            if(item.productSpecs && Array.isArray(item.productSpecs) && item.productSpecs.length){
                this.productList = [];
                this.product = '';
                this.beforeSelGoods(item);
                return;
            }
            this.addProduct(item.id, true,null,true,null);
            this.productList = [];
            this.product = '';
        },
        // 获取会员登录二维码
        getVipCode: function () {
            if ( !this.vipLoginApiBtn ) {
                return;
            }
            this.vipLoginApiBtn = false;

            this.showEnterPhone = true;
            this.EnterPhone = '';
            this.vipPhoneList = '';
            this.$http.get('order-binding?storeId='+this.storeId+'&orderId='+this.orderId).then((res)=>{
                this.isqrcode = true;
                setTimeout(()=>{
                    $('#vipQrcode')[0].innerHTML='';
                    let vipQrcode = new QRCode("vipQrcode", {
                        text: res.data,
                        colorDark : "#000000",
                        colorLight : "#ffffff",
                        height: 200,
                        width: 200,
                        correctLevel : QRCode.CorrectLevel.H
                    });
                },200)
                this.vipLoginTimer = setInterval(()=>{
                    this.vipLoginQuery();
                },2000)

                this.vipLoginApiBtn = true;
            }).catch(( err )=>{
                this.vipLoginApiBtn = true;
            })
        },
        // 解绑会员
        cancelVip: function () {
            if(this.isBindCoupon){
                this.relieveCoupon(true);
                return;
            }
            this.$http.put('orders/'+this.orderId+'/relieveMember').then((res)=>{
                this.vipData = '';
                let body = res.data;
                this.choiceArr = body.items;
                this.totalPrice = {
                    count: body.count, // 总数量
                    total: body.total, // 总计金额
                    discount: body.discount, // 优惠金额
                    amount: body.amount, // 最终价格
                    removeZero: body.removeZero, // 最终价格
                }
            }).catch(()=>{

            })
        },
        // 会员登录轮询
        vipLoginQuery: function ( boo ) {
            this.$http.get('query-binding?orderId='+this.orderId+'&type=BINDING').then((res)=>{
                if ( res.status === 200 ) {
                    this.closeVipCode( boo );
                    this.vipData = res.data;
                    this.vipData.amount = this.vipData.amount.toFixed(2);
                }
            }).catch(()=>{
                clearInterval(this.vipLoginTimer);
                this.isqrcode = false;
            })
        },
        // 关闭二维码弹框
        closeVipCode: function ( boo ) {
            if ( boo ) {
                this.showPayBox = true;
            }
            this.isqrcode = false;
            this.clerkMemberSwitch = false;
            clearInterval(this.vipLoginTimer);
        },
        // 获取充值规则
        getChargeRules(){
            let storeId = localStorage.getItem('storeId');
            this.$http({
                url:API_BASE_URL+"v1/pos/charge-rules",
                method:"GET",
                params:{
                    storeId
                }
            }).then(res=>{
                this.chargeRules = res.data;
            });
        },
        getNotes(){
            let storeId = localStorage.getItem('storeId');
            this.$http({
                url:"get-store-msg",
                method:"GET",
                params:{
                    storeId
                }
            }).then(res=>{
                if(res.status == 200){
                    this.notesArr = res.data;
                    let selNotes = JSON.parse(localStorage.getItem("selNotes"));
                    if(selNotes && res.data.length){
                        this.notes = res.data[0].message;
                    }
                }
            });
        },
        getOrder(){
            console.log("klkl");
            this.$http.get('orders/' + this.orderId).then((res)=>{
                if(!res.data.id){
                    sessionStorage.removeItem("orderId");
                    this.clearOrder();
                    return;
                }
                let body = res.data;
                this.choiceArr = body.items;
                this.totalPrice = {
                    count: body.count, // 总数量
                    total: body.total, // 总计金额
                    discount: body.discount, // 优惠金额
                    amount: body.amount, // 最终价格
                    removeZero: body.removeZero, // 最终价格
                }

                this.$http.get('orders/' + this.orderId).then((res)=>{
                    if(!res.data.id){
                        sessionStorage.removeItem("orderId");
                        this.clearOrder();
                        return;
                    }
                    let body = res.data;
                    this.choiceArr = body.items;
                    this.totalPrice = {
                        count: body.count, // 总数量
                        total: body.total, // 总计金额
                        discount: body.discount, // 优惠金额
                        amount: body.amount, // 最终价格
                        removeZero: body.removeZero, // 最终价格
                    } 

                    if ( res.data.memberId ) {
                        this.$http.get(this.storeId+'/members?memberId='+res.data.memberId).then((res)=>{
                            this.vipData = res.data;
                            this.vipData.memberId = res.data.id;
                            this.vipData.amount = this.vipData.amount.toFixed(2);
                        });
                    }
                    // 
                    // this.searchOrderType();
                });
            });
        }
  	},
  	created: function () {
        m$.setTitle('点单');
  		if ( !localStorage.getItem('storeId') ) {
  		  	this.$router.push({path:'/login'});
  		} else {
            this.storeId = localStorage.getItem('storeId');
            this.getGoods();
            // 获取充值规则
            this.getChargeRules();

            this.$http.get('/stores/'+this.storeId).then((res)=>{
                this.clerkCashSales = res.data.clerkCashSales;
                localStorage.setItem("rechargeLimit",JSON.stringify(res.data.rechargeLimit));

                sessionStorage.setItem("discount",JSON.stringify(res.data.discount));
                sessionStorage.setItem("zero",JSON.stringify(res.data.zero));
            });
            
	        // 判断是否有缓存订单
	        if ( sessionStorage.getItem('orderId') ) {
	        	this.orderId = sessionStorage.getItem('orderId');
                
                // 如果用户刷新了界面，此时还原金额
                this.$http({
                    url:API_BASE_URL+"v1/pos/return-order",
                    method:"POST",
                    data:{
                        orderId:this.orderId
                    }
                }).then(res=>{
                    console.log(res);
                    if(res.data.result.code == 200){
                        // this.nowSelCoupon = Array.isArray(body.couponInstances) ? body.couponInstances[0] : body.couponInstances;
                        let body = res.data.data;
                        this.choiceArr = body.items;
                        this.totalPrice = {
                            count:    body.count, // 总数量
                            total:    body.total, // 总计金额
                            discount: body.discount, // 优惠金额
                            amount:   body.amount, // 最终价格
                            removeZero:   body.removeZero, // 最终价格
                        }
                        this.getOrder();
                        // this.relieveCoupon();
                    }else if(res.data.result.code == 400){
                        this.createOrder();
                    }
                });
	        } else {
	        	// 生成订单
                // this.createOrder();
	        }
  		}
  		/*let that = this;
  		// 离开界面时，取消订单
  		window.onbeforeunload = function () {
  		    if( !(that.choiceArr.length >= 1) ){
  		        that.$http.delete('orders/'+ that.orderId).then((res)=>{

  		        })
  		    }
  		}*/
      },
      updated() {
        //   console.log(this.right_goodsScroll)
        //   setTimeout(()=>{
                // this.goodsListScroll.refresh();
                // this.right_goodsScroll.refresh();
                // this.left_barScroll.refresh();
        // },1500)
      },
  	mounted: function () {
        try {
            this.getRegionList();
        } catch (error) {
            console.log(error);
        }
        try {
            let leaseProductEnabled = localStorage.getItem("leaseProductEnabled")
            if(leaseProductEnabled == "true"){
                this.leaseProductEnabled = true;
            }else{
                this.leaseProductEnabled = false;
            }
        } catch (error) {
            
        }
        // alert($(document).height());
        // $('.takeOrder').height($(window).height());
        // 判断来自微信浏览器
        if(isWeiXin()){
            if ( window.screen.height - $('.takeOrder').height() < 30) {
                $('.takeOrder').css('paddingTop', '64px');
            }
        }
        // this.goodsListScroll = this.$createScroll('goodsList');
        // this.right_goodsScroll = this.$createScroll('right_goods');
        // this.left_barScroll = this.$createScroll('left_bar');
        this.carGoodsBoxScroll = this.$createScroll('carGoodsBox');
        // setTimeout(()=>{
                // this.goodsListScroll.refresh();
                // this.right_goodsScroll.refresh();
                // this.left_barScroll.refresh();
                // $('.takeOrder').height($(window).height());
        // },1500)

        this.animateDom = $('.goodAnimate');
        this.carDom = $('.shopCar .carImg');
        function isWeiXin() {
            var ua = window.navigator.userAgent.toLowerCase();
            if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                return true;
            } else {
                return false;
            }
        }
        let storePayMode = localStorage.getItem("storePayMode");
        if ( storePayMode == 'CASHIER' ) {
            this.isOnline = false;
            return;
        } else {
            this.isOnline = true;
        }

        setTimeout(()=>{
            let discount = JSON.parse(sessionStorage.getItem("discount"));
            let zero = JSON.parse(sessionStorage.getItem("zero"));
            this.showDiscount = discount;
            this.showZero = zero;
        },300);

        let url = window.location.href.split("#")[0];
        console.log(url);
        this.$http
        .get(API_BASE_URL+"wechat/scan?url="+url)
        .then(res => {
            console.log(res);
            // this.returnUrl = res.data.url;
            wx.config({
            debug: false,
            appId: res.data.appId,
            timestamp: res.data.timeStamp,
            nonceStr: res.data.nonceStr,
            signature: res.data.signaTrue,
            jsApiList: ["checkJsApi","scanQRCode"]
            });
        });
        this.getNotes();
        let selNotes = JSON.parse(localStorage.getItem("selNotes"));
        if(!selNotes){
            this.selNotes = false;
        }else{
            this.selNotes = selNotes;
        }
      },
}
</script>
<style lang="scss" scoped>
	@import "../../../static/css/common.scss";
	@import "takeOrder";
    .rent-out-wrap {
		position: fixed;
		top:0;
		right: 0;
		left: 0;
		bottom: 0;
		z-index: 10;
		background-color: rgba(0,0,0,0.59);
		.qrcode {
			z-index: 2;
		}
		#qrcode,.tit2{
			width: 2.5rem;
			height: 2.5rem;
			position: absolute;
			bottom:27%;
			left: 50%;
			background-color: #ccc;
			transform: translateX(-50%);
		}
		.tit2{
			bottom: 30%;
			width: 100%;
			background-color: transparent;
			padding-left: 20%;
			color: #fff;
			font-size: .32rem;
			font-weight: bold;
		}
		.form-wrap{
			position: absolute;
            top:50%;
			left: 50%;
			transform: translate(-50%,-50%);
			background-color: #fff;
			width: 80%;
			border-radius: 5px;
			text-align: center;
            padding-top:0.25rem;
            .close-btn{
                position:absolute;
                right:-.25rem;
                top:-.25rem;
                display:flex;
                justify-content:center;
                align-items:center;
                font-size:.4rem;
                width:.5rem;
                height:.5rem;
                border-radius:.25rem;
                background:#ccc;
                color:#000;
            }
			.tit{
				font-size: .32rem;
				font-weight: bold;
				text-align: left;
				padding: .2rem;
			}
			.form-item{
				padding: .05rem .35rem 0 .35rem;
				.form-name{
					width: 100%;
					text-align: left;
					padding-bottom: .1rem;
					font-size: .25rem;
					color: #db5f32;
				}
				.item-cont{
					width: 100%;
					position: relative;
                    height:.9rem;
                    display: flex;
                    align-items:center;
                    select{
                        padding:0;
                    }
					input,select{
						width: 100%;
						text-align: left;
						margin: 0;
						border: none;
						box-sizing: border-box;
						background:none;
						font-family: ".PingFangSC";
						font-size: .28rem;
						height: .7rem;
						border: 1px solid #ddd;
						border-radius: .1rem;
						padding-left: .1rem;
					}
					.get-code{
						position: absolute;
						top: 0;
						right: 0;
						display: inline-block;			
						width: 2rem;
						height: .7rem;
						line-height: .7rem;
						text-align: center;
						background-color: #ccc;
						color: #fff;
						font-size: .25rem;
					}
				}
			}
			.sub-btn{
				width: calc(100% - .7rem);
				height: .7rem;
				border: none;
				background-color: #db5f32;
				color: #fff;
				border-radius: .1rem;
				margin-bottom: .25rem;
                &.cancel{
    				background-color: #ccc;
                    margin-bottom:0;
                }
			}
		}
        .rent-list{
            padding:.2rem;
			.rent-head{
				width:100%;
				height:.5rem;
				background:#059313;
				color:#fff;
				display:flex;
				align-items:center;
                font-size:.28rem;
				.it{
					display:inline-block;
					text-align:center;
					width:50%;
				}
			}
			.rent-goods{
				background:#f4f4f4;
				.r-li{
					min-height:.8rem;
					width:100%;
					display:flex;
					flex-wrap:wrap;
					align-items:center;
                    font-size:.24rem;
					.it{
						width:50%;
                        font-size:.24rem;
						display:inline-block;
						text-align:center;
					}
				}
			}
		}
		.tit2{

		}
		.tip{
			position: absolute;
			left: 50%;
			transform: translateX(-50%);
			bottom: 20%;
			color: #ccc;
			font-size: .25rem;
			width: 100%;
			white-space: nowrap;
			text-align: center;
		}
		.vip-charge{
			font-size: .3rem;
			width: 3rem;
			height: .68rem;
			border:1px solid #db5f32;
			border-radius: .34rem;
			text-align: center;
			line-height: .68rem;
			color: #db5f32;
			position: absolute;
			bottom: 10%;
			left: 50%;
			transform: translate(-50%,0);
		}
	}
</style>
